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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


text:
continuous print of button Pushed
When pushing a button I want to read the value...once.
If I push(hold) the button I get a continuous print of button1Pushed
    if(button1State == LOW) {
     Serial.println("button1Pushed");
  }

But if I try to solve it like this, nothing happens, not a single print. What am I missing?
 int button1State = digitalRead(button1);
  int lastButton1State;

  if(button1State != lastButton1State){
      if(button1State == LOW){
        Serial.println("button1Pushed");
               }
        }

  lastButton1State = button1State;

lastButton1State is not initialized and therefore has no strictly defined value. In your case, it appears to have a value of 0 (which is random, it's not due to implicit initialization, which is only done for global variables). The condition if(button1State != lastButton1State) becomes true only if the button is released.
You can check that by changing
if(button1State == LOW){
  Serial.println("button1Pushed");
}

to
if(button1State == HIGH){
  Serial.println("button1 released");
}

The following should work:
int last_button_state=HIGH; // initialize to HIGH, so the button does not teigger on very first iteration
void setup () {
  // whatever you want to do here
}
void loop() {
  int button_state=digitalRead(button1);
  if (button_state!=last_button_state && button_state==LOW) {
    Serial.println("button pressed");
  }
  else if (button_state!=last_button_state && button_state==HIGH) {
    Serial.println("button released");
  }
  last_button_state=button_state;
}

your suggestion gives me the same result, still an endless repeat of the serial.print

Did you see the change I made? I forgot to add last_button_state=button_state;... if it still doesn't work, please post the entire code

I tried your suggestion in a blank sketch and it works!
There is probably something buggy in the rest of my code (its pretty huge..for me..as a amateur)

Found it! I put int last_button_state=HIGH; in the loop.....pff..time for bed

@Niles please see my comment

source: Stack Exchange

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

sort: votes


text:
FastLED fade WS2812B
Learning how to program with Arduino, but the learning curve is out of my league.
I have this
    #include <FastLED.h>
    #define NUM_LEDS 4
    #define DATA_PIN 3

        CRGB leds[NUM_LEDS];

           void setup() {
       FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
   }

       void loop() {
      // Turn the first led red for 1 second
      leds[0] = CRGB::Green;
      leds[1] = CRGB::Red;
      leds[2] = CRGB::Green;
      leds[3] = CRGB::Red;
      FastLED.show( 99 );
      delay(1000);

      // Set the first led back to black for 1 second
      leds[0] = CRGB::Red;
      leds[1] = CRGB::Green;
      leds[2] = CRGB::Red;
      leds[3] = CRGB::Green;
      FastLED.show( 99 );
      delay(1000);
    }

So, I want them to fade from green to red.
led 1 is green, and led 2 is red
I should probably program this in a different way, but I don't know how.
Any ideas are welcome!

You understand that you'll be fading through yellow, right?

At the moment you have become used to working with pre-defined named colours, like CRGB::Red and CRGB::Green.  Those are just symbolic names for combinations of numeric values for red, green and blue.
So by using numeric values and varying them slightly over time you can create fade effects.  I am not personally familiar with that library or class, so I cannot tell you how to do it, but reading the documentation should show you how you can use variables to specify each of the colour components as a single colour.
As for how to fade from red to green - since they are two completely separate colours (they use separate colour channels in the LEDs) there are two main ways of doing it:

Start with red on full and green off. Slowly increase green to get yellow. Then slowly decrease red to get green.
Start with red on full and green off. Slowly increase green while slowly decrease red. At 50% they will cross over.

//start with full red
leds[0].red = 255;

//slowly add green
for( int i=0; i<256; i++ )
{
  leds[0].green = i;
  delay(10);
}

// slowly subtract red
for( int i=255; i>=0; i-- )
{
  leds[0].red = i;
  delay(10);
}

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


text:
Sim800l gsm module cannot connect gprs data
I am a rookie to arduino. I am trying to access MQTT server using Sim800l coreboard GSM module with Adafruit Fona/Tinygsm library but failed.So I decided to check http GET/POST request with AT command first.In AT commands all the basic commands following www.exploreembedded.com/wiki/Setting_up_GPRS_with_SIM800L  works fine  but whenever I make a GET request by "AT+CIPSTART=" module restart itself.I also tried seeduino library GPRS_HTTP example, it gives me "error:CIPSTART" and restarts module.Though this code worked one time only,this is the code
#include <gprs.h>
#include <SoftwareSerial.h>

char http_cmd[] = "GET /media/uploads/mbed_official/hello.txt
HTTP/1.0\r\n\r\n";
char buffer[512];

GPRS gprs;

void setup() {
Serial.begin(9600);
while(!Serial);
Serial.println("GPRS - HTTP Connection Test...");
gprs.preInit();
while(0 != gprs.init()) {
 delay(1000);
 Serial.println("init error");
}
while(!gprs.join("gpinternet")) {  //change "cmnet" to your own APN
  Serial.println("gprs join network error");
  delay(2000);
}
// successful DHCP
Serial.print("IP Address is ");
Serial.println(gprs.getIPAddress());

Serial.println("Init success, start to connect mbed.org...");

if(0 == gprs.connectTCP("mbed.org", 80)) {
  Serial.println("connect mbed.org success");
}else{
  Serial.println("connect error");
  while(1);
}

Serial.println("waiting to fetch...");
if(0 == gprs.sendTCPData(http_cmd))
{
gprs.serialDebug();
}

//  gprs.closeTCP();
//  gprs.shutTCP();
//  Serial.println("close");
}

void loop() {

}

also tried this commands and module got restarted after AT+HTTPACTION=0 this last command

module power and sim configure are fine as far I know,please help me find out what am I doing wrong?Sorry for making this long.please ask me if I couldn't make the question clear.TIA

How exactly are you powering the SIM800?

I have connected a buck booster with arduino 5V pin and got 4V for SIM800l as it works between 3.6-4.2 . also while using AT+CIICR or
AT+SAPBR =1,1 command, module blinks continuously  until making a GET request I don't know if it is normal or not  and then restarts.

it can make calls ,send text ,shows network status. doesn't  restart then.

I get it now , a stable power source is the answer. arduino with usb can give right amount of Volts but it lacks stable power(amps i guess) while making a TCP connection, that's why module keep restarting.Although it works fine with call, text etc. powering arduino with an AC adapter solves my problem ,now it can connect to mqtt too.Thanks

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


text:
Is there a way of turning a computer into a Arduino type board?
The Arduino's processing power is not sufficient for some of the tasks I would like it to perform...
I'm thinking of making a Home Automation System and would like some serious processing power at the center of it all.
So I'm wondering if I can just use standard PC parts to essentially put together my own board?!?
Is this possible???

Is there a reason why you can't interface with the Arduino but process with the computer?

Just connect an Arduino to the PC and do the heavy processing on the PC  and then tell the Arduino over serial what to do. Or use something like an Raspberry Pi. But it really depends how your home automation system is set up. If you are communicating with your other devices over WiFi or Bluetooth you just need a normal PC with WiFi/Bluetooth. What do you actually want to do with a powerful "Arduino", that you can't do with just a PC/Arduino?

Why not use standard PC parts and make a PC?

The old IBM PCs ran at 4.77 MHz. Your Arduino runs at 16 MHz. I'm a little sceptical that it can't keep up with turning on and off your lights in a timely way.

If arduino is not giving you serious processing power, you can use Raspberry pi, beagle board, toradex board to make your own embedded PC. I guess these are enough for your application

An mbed board would give more cpu power (most are in the 100MHz Arm M3 region, some are slightly faster M4s) while staying bare metal like an Arduino. If that's not enough I'd agree with a Pi rather than a PC.

For home automation, it IMHO makes sense to have a central "server" (raspberry pi is enough) that can serve webpages. This webpage would be connected to a "gateway" that can send TCP/IP (or http) commands to Arduino's or ESP8266’s. This way, you can make use of your existing network or wifi. The Arduino/ESP8266 will be vast enough to read a message, change an output according to the message and return an "OK". Which is all you need on an endpoint.

You could simply opt for a different platform? A Raspberry Pi or Beagle Bone? Either would probably have enough processing power and ram. The Onion Omega2 is a SoC with a 400Mhz CPU, 64MB of DDR2 RAM, 16MB of on-board flash storage, 802.11b/g/ WiFi at 150 Mbps, 18 digital GPIOs, I2C, SPI, and USB2.0, a full Linux Operating System, and it costs $5.
The Onion Omega

A regular Arduino uses an AVR, more "pimped" Arduino might go to ARM. Some special versions of Arduinos uses other chips, such as the ever iconic ESP8266.
For home automation, an ESP8266 is WAY enough. Using an ARM is quite and overkill for home automation. But I've never seen anybody using a full PC for it. Why? Because it is around 10-20 times more expensive. They require much more components and many other things.
Something close to a full PC that you can get is a Raspberry Pi (any version would do). They act like a small PC, some even use it as a laptop. See PiTop. The Raspberry Pi is stronger, more powerful, and much faster then any Arduinos. The Pi also has ethernet, a graphic interface, and an audio interface built in. That means that you can pretty much connect it to a monitor and it will work as a normal PC running either Windows or Linux. You can then watch a video, with graphics and sound, from the inthernet without external modules like you would need on an Arduino. Their only weakness is that it is harder to program them to read may sensors. That is why the Arduino is popular for covering that.
At the end of the day, it is your choice. I would personnally suggest an ESP8266. This module has many GPIOs, depending on the breakout that you have, and has WiFi built in. This is a great feature for home automation. Most home automation builders use this module.
If you have any questions about the informations I just gave you, comment it, I'll reply.

I assume he wants to make a controller with a WebUI/GUI and stuff. A ESP8266 won't be enough for that.

@gre_gor, actually, the ESP8266 can do a small web server with a VERY simple UI.

One of the Arduino ESP8266 examples is a web server with uploadable files (in SPIFFS). Adding the appropriate routes is all it takes to make a decent web controller.

Adding to Candice the Cyborg's answer I would go for esp8266-12 (for a specific breakout board) if you choose to go down that route-where Candice the Cyborg writes " "pimped" Arduino" this does not refer to the esp8266.
But if you're using a PC to begin with you might as well get a PC based hardware to do the home automation. Arduino can't compete with PC for power and features-but it was never designed to.
You could try linking multiple Arduino's together communicating through the serial port pins-essentialy it would work something like a parallel processor. If it's just run of the mill home automation things then this can be broken down into a parallel problem. If you update your question with more info I can give you a more specific answer. I mean if your tasks only require a little extra processing power then it may be possible to do using an addition Arduino for example.
The cheapest way to set up a PC for home automation is probably add in a parallel port card-there are project around the internet that show how to use a PC for home automation with parallel port-if you don't have a parallel port then you can get a parallel port card for less than $5-so its cheap way to get IO pins-this was the way things could be done before the days when Arduino existed.
Using an Arduino UNO or the like is not a good idea for interfacing to USB devices -like cameras -if you has that in mind- that's because the ATMEGA chip does not natively support USB host and it's non-trivial to implement USB interface host yourself on Arduino-it would take deep knowledge of USB protocol as a minimum.
Sorry to say it on an Arduino site- but it may turn out cheaper to use a full PC (if your project can be run on an old PC you can get cheap or free) with no Arduino- a PC after all has much more hardware already built into it -lots more ports, video output and so on. Adding the cost of shields to do something similar on Arduino could cost a lot-it depends on the specifics of your question -which you don't give.

One thing a PC lacks, which is kind of critical for working with sensors and things, is easy access to IO.
A PC has a number of buses, but no GPIO pins. To get any form of GPIO you will have to add extra hardware in the form of PCI cards, etc. Those kind of things, since they are not widely used, are rare and hence expensive.
People have "hacked" their PC hardware before now to add I2C devices to the I2C bus that is present on all DDRx DIMM slots (used for module identification) and using that you could add I2C IO expanders to get some GPIO pins - however that is not easy to do, and then you have the problem of programming it on top of that.
The most flexible solution is to use USB. Using the PC as the "core" processor for heavy data processing, image capture, network communication, etc is simple enough and commonly done. Then using USB you interface to the devices you want to work with - cameras, etc. You can get USB-based IO boards which provide different forms of IO communication, such as TTL UART (FT232 boards, etc), parallel GPIO, I2C buses, SPI, etc. Of course, programming those things becomes somewhat tricky, and you may end up with a massive number of dongles on your computer to interface with the large number of things you want to connect to.
So a more flexible and sensible approach is to create your own USB interface to your sensors and other items. And one of the best and easiest systems to do that is, of course, the Arduino and Arduino-like boards.
An Arduino, or multiple Arduinos, become a sensor interconnect board which you program to communicate with whatever you need to communicate. That can then pass data back to the PC through USB which then performs the heavy number-crunching and what have you. Data can then be passed back through the USB to the Arduino for controlling other things (fans, lights, heaters, whatever).
So yes, you can use a PC as a powerful processor system in a larger plan, but the PC itself cannot replace an Arduino.
Of course, all this is assuming you have a PC to waste on the project, or you have the requirements of massive amounts of processing power that you can't get from any decent micro-controller or SoC.
One thing to remember: there are micro-controllers available cheaply today with considerably more power than the first pentium PCs - I regularly work with 200MHz MIPS based MCUs with embedded FPU - that's 3.33 times more powerful than the first pentiums (and without the floating point bug ;) )
The current Raspberry Pi embedded Linux computers provide all the GPIO and interfacing you should need at a tiny fraction of the price of a PC. They are (as of version 3) a quad-core 1.2GHz 64-bit SoC. The same quad-core 1.2GHz core that is used in many smart phones. That's more powerful than my laptop.

One approach that I am using in a project right now is to use both an
Arduino Mega 2560 (for interfacing the hardware, as it has many
5 V GPIO pins, analog inputs and very predictable timings) and a
Raspberry Pi (for running a Node.js-based Web server). They
communicate through a level-shifted serial link, using a protocol
roughly shaped on this command line interpreter.
This way I have both the ease of interfacing hardware provided by the
Arduino and the power of a real computer.
Not saying it is the right solution for you, but as you did no provide
details on your project's requirements, we can only make suggestions.


text:
What can I do in this situation
I only currently have 2 arduinos and I find that any project I build I feel bad because I have to rip it apart to get the arduino because I want to build something else. Is there a way to get arduinos for cheap? (I'm new to arduino)

Possibly not "genuine" Arduinos, but eBay has many sellers in China and Hong Kong who sell boards that are just like Arduinos, if you're willing to wait several weeks for delivery.
I was able, just now, to find an Arduino UNO compatible board for US$3.59, plus less than $2 shipping to the US. Note that they do not come with tech support, and none of the profit goes to support the official Arduino developers.


text:
void loop followed by other "void" expressions
I hope this is a simple request from a newcomer to Arduino and programming. I have understood that once a program enters a void loop section, it loops round indefinitely. However I have recently seen examples of sketches where another void $$$$$ section follows the closure (by}) of the void loop. As I write this, I am looking at one example concerning a 7 segment display where "void Num_Write(int)" follows the closure of the void loop. If the "loop" section does just that, as I have been lead to believe, how is a following section accessed?
Thank you,
Rob

By calling it. https://www.tutorialspoint.com/cplusplus/cpp_functions.htm

It's also covered in the Arduino reference: https://www.arduino.cc/en/Reference/FunctionDeclaration

To top it off : http://www.cplusplus.com/doc/tutorial/functions/

The void loop() section is a function, the same as void setup() is a function.  When you start you Arduino program another function, that you can't see in the IDE, call setup() and then calls loop() repeatedly.
These other function you have seen, i.e. void Num_Write(int n) can be called from either setup() or loop() and they will execute their instructions before returning to the function that called them. Its also possible the Num_Write() may call other functions before it returns controller to the function that called it.
The type void is used to represent nothing (its actually more complex than that, but for this level of explanation nothing will do).  Other functions may return other types int, char, bool for instance.  So if we had a function like this:
int theMeaningOfLife(void)
{
  return 42;
}

This is a function that returns an int (a number) so you would call it like this:
void setup()
{
  int number = theMeaningOfLife();
}

There is one catch, the function has to be declared BEFORE it is used, this allows the compiler to know what you are referring to.  The simplest way of doing this is to write the function above the function that is calling it.  The second way is to just write the function's signature above the function using it, i.e.:
int theMeaningOfLife(void);

void setup()
{
  int number = theMeaningOfLife();
}

The best way (but not always practical on an Arduino) is to have all the function declarations in a header file (.h) and the code in a .cpp file.  (Have a look a library to see what I mean).
Summary
There is only one function that is called repeatedly and that is the loop function.
Just because a function returns void doesn't mean its going to loop repeatedly.

You wrote: “the function has to be declared BEFORE it is used”. Actually, the Arduino IDE runs your code through a pre-processing step that does that for you, meaning you do not have to do it yourself. I still would consider good practice to stick to this rule, if only because it makes the code compilable outside the IDE, e.g. with a Makefile.

@EdgarBonet - Thanks, I never knew that.  I think I should forget it though, otherwise I'll start trying it at work and end up pulling my hair out trying to work out why [it] won't compile. :)


text:
Finding and loading "libraries"
I am 6 months into my Arduino Uno work and I would like a step by step way to find and download a "library". I work using WINDOWS and WORD and although I was eventually successful in getting a 7 segment display library to download and work, I must say I could not do it again since the path I followed was far from clear due to my lack of understanding about basic computer stores etc. I have enjoyed my work with the Uno but I have been very disappointed at lots of "help" offered on other sites since they assume I know far too much. It is a skill to be able to communicate with we lesser people so I am really hoping a step by step guide is possible.
Thanks

.....  Word?!?! .....

youtube has a ton of non-hardcore arduino vids, including lib vids

Usually, the documentation is the correct place to start.

A lot of the Adafruit tutorials are targetted at absolute beginners.

Start with the newest Arduino IDE. At this moment that is version 1.8.1.
Try to find the Library Manager. Via the menu: Sketch / Library...
In the Library Manager there is a input field in the upper-right corner where you can search for libraries.
If you can not find the library, then the next step is to download a zip file from Github. There is probably a green button "Clone or Download" on the right side with that project on Github. Use it to download that library and store it. Do not unzip it. In the Arduino IDE in the menu via: Sketch / Library... there is a option to install a .ZIP file. Use that to install the library from Github.
Your projects are probably at: Documents / Arduino
There is also a folder: Documents / Arduino / libraries
That is where the installed libraries will end up. That means you can also add libraries to that folder. Each library in its own sub-folder.


text:
Car freaks out on CANBUS shield connection
So, I'm trying to connect to my car's CAN-BUS (via the OBD2). I initially ordered a cheep shield then an even cheaper module to provide connection between my uno and the car.
Using the module I was able to use some of the example libraries to successfully connect to the car and even get some IDs out. There was no data alongside the IDs so I figured my module needed upgrading.
I bought the seeedstudio shield and used their libraries. At first I had the CANH and CANL connected into the car before starting it but that seems to have overwhelmed the car and I couldn't start it, it behaved as if the battery was dead.
Eventually when it recovered I tried again, this time the car was already running. Havig the CANL&H connected and the shield attached to the arduino and using the example sketches, when I provided power to the Arduino via the USB port the car started freaking out. The dials went crazy and started moving left to right and all sorts of warning messages started appearing on the dash - "check airbag", "engine motion something.." Disconnecting the shield from the car stops the freaking out and removes the errors displayed.
Any idea what's going on ?
Also should any of these be soldered to each other as the manual suggests there's some cutting and soldering there but I haven't cut nor soldered anything and this is how the shield arrived.
Worth pointing out that I tried connecting to both Pin6 as the proper CANH and also Pin1 as that one was discovered to also provide CANBUS data for the cabin. Here's the obd2 diagram pinout for my car.

This is old but for the sake of anyone who finds this. I cannot say for sure but Im pretty sure what you were seeing (gauges acting crazy) is due to your can card trying to communicate across the bus network at the same time as another moduL. If you were using this on an older car only one module “speaks” at any given time. Currently this is the same problem i am having which brought me to your post as i am trying to figure out which module in my car has a problem. My problem is so intermittent that back probing the individual modules doesnt help as the problem may only surface once every week

continuation of Shizzavip's answer converted to comment: ... or two. Gauges go wack. Either it will take care of itself after few minutes of driving or I can turn off and on and back to normal. So i am trying to build a arduino with canbus shield to just sniff so i can log to memory card and try and figure out which module is having problem.

You are lucky you did not damage your vehicle. The bus is not the same on all cars.

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


text:
Using Browser window to display sensor values in realtime
The title pretty much says it all:
What would be the most obvious way to setup the Arduino (shields?), the Sketch (libraries?) and PC (webserver, ajax, plain html?) so that I get the following system working:

I open some page in a browser. The page has some labels/fields/values;
I power up Arduino, which is connected to some sensors (or even potentiometers);
The sensor values display keep being constantly updated in the page, with a sensible refresh rate (the fastest as possible, as to control some browser-based game for example);

The fundamental idea here is to use the Browser, and not some other GUI toolkit, or Processing, or the command line.

I guess there are a number of ways to tackle the problem. Using the Ethernet shield is probably the most intuitive option, but this isn't something I have explored in too much detail - I would usually opt for other micros at this stage and I am confident you will get an answer from someone else detailing this.
To get the most out of the Arduino and leverage what the Arduino is good at, I would probably make a C# console application or Windows service which communicates with the Arduino over serial, and use the 'System.Web.Http.SelfHost' assembly to make the data available through a RESTful web service which a html page could use JQuery to poll for information. It would be pretty easy to extend this to push the data to the page using SignalR.
The fundamental drawback of this architecture is that your device isn't serving the website, so these must be hosted somewhere else, or run from flat files. Also a PC must be attached to facilitate the data transfer over serial and provide the web service.
To get started you will want to familiarise yourself with c# and the SelfHost module, and WebApi 2.0 if you aren't already, this is all covered here, and of course you will need Visual Studio Community edition or greater to start creating projects.
Next, write a Windows Service or Console Application which implements an object model holding your data, and updates this periodically with the Arduino via serial.
The Self Host module is pretty incredible in that it allows you to add a web interface to any .Net application very easily, and directly manipulate your model. The tutorial linked above is very easy to follow, and can easily be adapted.
For testing and development purposes, I would highly recommend Postman, which can be used to test and trigger your API endpoints. It's a comprehensive and well polished tool specifically for this job.
In terms of the network logistics, I would then use JQuery to make periodic posts to the self-host service in the same fashion that Postman would. You can use the function call backs to trigger successive queries on completion to maximise the data refresh rate without causing excessive consumption. A time interval would be another option you could consider between requests, and is discussed in this article on polling.
The typical Ajax request structure would look something like this:
$.ajax({
    url: 'yourApiMethodAddress',
    type: 'get',
    error: function (jqXHR, status, ex) {
        /* Something went wrong. Maybe you could stop
           the update process and show a message and
           a retry button. */
        console.log("Error: " + status);
        console.log(ex);
    },
}).done(function (data) {
    // Update page with information stored in 'data'. View console for hints
    console.log(data);
});

I would recommend using Twitter Bootstrap in your webpage file to pretty things up and maintain readability. Don't forget to include the javascript and css files for both Bootstrap and JQuery in your html document (if used).
In summary, I would recommend implementing an application which runs on a computer attached via USB/Serial to the Arduino, with the .Net Self Host module utilised to provide a RESTful API. This API can then be polled from a html page using javascript and JQuery to obtain the information and update the page.
I hope this information helps, and as there a lot of moving parts I didn't provide many code examples for simplicity sake. If you find this useful and would like more information adding, mention it in the comments and I will update my answer.

Your question actually exists out of multiple questions...
1. How to connect arduino to network/internet.
I would suggest using a cheap WIFI module or Ethernet module
2. How to send values from arduino over ethernet.
The fastest would be using a direct connection (TCP/IP or UDP?)
3. How to receive values from arduino over ethernet on a PC.
The problem with this would (I think) be that a webserver usually does not enable a direct TCP/IP connection, but instead would use HTML to transfer data/webpages. But I'm not a web-developer at all. I would create a dedicated program in processing/c++/python or something similiar.

The first two parts I think are not difficult, I guess. But the third part is the part I am actually interested (although I must agree it's not an Arduino question...)

I'm actually also interested in this, (I'm at 'work' now) but I suggest you check out some similiar projects on the internet.
You're not interested in running the webserver on arduino are you? http://www.arduino.cc/en/Tutorial/WebServer
You want to make the arduino a controller/client from an online game?
The last part is indeed a bit off-topic, but there might be people on here who have knowledge on it or have done a similiar project with arduino.
You should check if you can receive raw tcp/ip on a webserver. As webserver vs dedicated program is quite a difference


text:
Using shiftin() and shiftout() with the same circuit - what to consider?
I am designing a smart (or at least I hope so) onboard bicycle light system. The system will have an Arduino (currently prototyping with UNO) and a subsystem composed of a "panel" of buttons and leds.
This panel should stay at the handlebar, connected by multi-wire cable to the Arduino located elsewhere on the bicycle.
In order to read an arbitrary number of push-buttons, I plan to use CD4021 IC with shiftIn() function. And, in order to turn an arbitrary number of leds on and off, I plan to use 74HC595 IC and the shiftOut() function.
My doubts are: what should I consider in order to do so?

How many wires should I need to connect an arduino to the panel circuit containing the ICs? I believe it is 8 wires (two for the power, three for shifting in [latch, clock, data], and three for shifting out), right?
Can I use any pin I want? Or is it required to use specific pins?
Is that the "right way" of doing this? Any suggestion or improvement is welcome!

If you can get your head around it, using SPI will let you output to the '595 and input from a shift register (I would avoid CD4k unless you're prepared for its shortcomings) at the same time. And there are a number of GPIO chips that use I2C, which will let you avoid having to deal with shifting altogether.

I'd recommend drawing a schematic of your circuit.  Not only will that make it clear in your own mind, it will aid the folks in the forum to visualize the picture.  Also, once you have the schematic, it will be much easier to construct your physical circuit as you will now have a blue print to follow.

@IgnacioVazquez-Abrams now you got me curious: Since this is the IC used on shiftIn() tutorial, what would these shortcomings be? What other shift register could be used instead? Also, the I2C tip is interesting, are those parts expensive in comparison? How should I search for one, and what would be a good 8 channel "equivalent" to the parts I mentioned?

CD4k parts have the drive strength of a wet noodle and the speed to match. They will work in that specific application, but do not get too used to them until you learn more about electronics and why their differences matter.

As for I2C, there are many options available, some a bit more pricy than others. The basic chip is the MCP23017, which has 16 GPIOs that can be used in any combination of input or output, with optional pullups, pin change interrupt support, etc., and up to 8 can be put on a single bus. It even comes in a SPI variant if you need to access it faster. There are other options such as the TCA6424A, but they come in more exotic packages that you may not be ready for.

@IgnacioVazquez-Abrams thanks very much for your valuable tips. You see, my question was a bit like "is what I am trying to do, and how I'm planning to do it, a good idea, or are there better ways?", so if you care to summon your suggestions as an answer, I would be glad to accept it. I don't know practically anything about I2C or SPI, but the MCP tip sounds like the right way to go, EXCEPT that I wasn't planning to use SMD, but actually through-hole, DIP ICs on a veroboard (or equivalent). Is there a through-hole version of that?

If you follow the link and examine the datasheet you'll see that the MCP23x17 is available in DIL, among other packages.

I found this library from Adafruit for that chip, sounds definitely the way to go: https://github.com/adafruit/Adafruit-MCP23017-Arduino-Library

I have a post here about using an I2C 16-port port-expander: http://www.gammon.com.au/forum/?id=10945
That would use 4 wires for I2C (power, ground, SDA, SCL) or there is an SPI version which would require an extra wire (power, ground, SCK, MOSI, MISO).
I'm not sure about noise over your cable runs, on a bicycle presumably electrical noise is low, so either one might suit. This is the chip that  Ignacio Vazquez-Abrams mentioned in his comments. Any of the 16 ports can be configured as inputs or outputs as you desire, plus it can raise an interrupt on a change on an input pin.
You might find that the maximum current limits for output may not be adequate for your LEDs (the datasheet says maximum of 25 mA per output pin, plus a maximum of 125 mA for the whole chip). You could work around this with driver transistors on the chip output, but this is more complexity.
There are higher-powered shift registers (eg. TPIC6B595) which can handle more per pin than the 74HC595.

Can I use any pin I want? Or is it required to use specific pins?

If you want to use I2C there are two specific pins dedicated to the I2C hardware. If you want to use SPI there are dedicated hardware pins as well (different ones) but you can also "bit-bang" SPI if you want.
See:
http://www.gammon.com.au/i2c
http://www.gammon.com.au/spi

Is there a through-hole version of that?

All the chips I mention here have through-hole versions.

Excellent! I'm new to digital electronics, so finding out all these things has been amazing! One more little question: if I don't need as much as 16 IOs, is there a similar chip with less IOs? I searched for some, and looks like PCAL6408 is a similar, 8-bit one, what do you think? Thank you very much!

As far as I can see the PCAL6408 does not come in a DIP package (through-hole). The MCP23017 seems to be selling on DigiKey for $US1.44 so that seems a reasonable price to me.

You're right, I though I have seen a DIP one, but no... Anyway, I'll look for the MCP, thanks!


text:
Classes and objects: how many and which file types do I actually need to use them?
I have no previous experience with C++ or C, but know how to program C# and am learning Arduino. I just want to organize my sketches and am quite comfortable with the Arduino language even with its limitations, but I really would like to have an object-oriented approach to my Arduino programming.
So I have seen that you can have the following ways (not exhaustive list) to organize code:

A single .ino file;
Multiple .ino files in the same folder (what the IDE calls and displays like "tabs");
An .ino file with an included .h and .cpp file in the same folder;
Same as above, but the files are an installed library inside Arduino program folder.

I have also heard of the following ways, but have not got them working yet:

Declaring a C++-style class in the same, single .ino file (have heard of, but never seen working - is that even possible?);
[preferred approach] Including a .cpp file where a class is declared, but without using a .h file (would like this approach, should that work?);

Note that I only want to use classes so that code is more partitioned, my applications should be very simple, only involving buttons, leds and buzzers mostly.

For those interested, there is an interesting discussion about headerless (cpp only) class definitions here: http://programmers.stackexchange.com/a/35391/35959

How the IDE organizes things
First thing, this is how the IDE organizes your "sketch":

The main .ino file is the one of the same name as the folder it is in. So, for foobar.ino in foobar folder - the main file is foobar.ino.
Any other .ino files in that folder are concatenated together, in alphabetic order, at the end of the main file (regardless of where the main file is, alphabetically).
This concatenated file becomes a .cpp file (eg. foobar.cpp) - it is placed in a temporary compilation folder.
The preprocessor "helpfully" generates function prototypes for functions it finds in that file.
The main file is scanned for #include <libraryname> directives. This triggers the IDE to also copy all relevant files from each (mentioned) library into the temporary folder, and generate instructions to compile them.
Any .c, .cpp or .asm files in the sketch folder are added to the build process as separate compilation units (that is, they are compiled in the usual way as separate files)
Any .h files are also copied into the temporary compilation folder, so they can be referred to by your .c or .cpp files.
The compiler adds into the build process standard files (like main.cpp)
The build process then compiles all the above files into object files.
If the compilation phase succeeds they are linked together along with the AVR standard libraries (eg. giving you strcpy etc.)

A side-effect of all this is that you can consider the main sketch (the .ino files) to be C++ to all intents and purposes. The function prototype generation however can lead to obscure error messages if you are not careful.

Avoiding the pre-processor quirks
The simplest way of avoiding these idiosyncrasies is to leave your main sketch blank (and not use any other .ino files). Then make another tab (a .cpp file) and put your stuff into it like this:
#include <Arduino.h>

// put your sketch here ...

void setup ()
  {

  }  // end of setup

void loop ()
  {

  }  // end of loop

Note that you need to include Arduino.h. The IDE does that automatically for the main sketch, but for other compilation units, you have to do it. Otherwise it won't know about things like String, the hardware registers, etc.

Avoiding the setup/main paradigm
You don't have to run with the setup/loop concept. For example, your .cpp file can be:
#include <Arduino.h>

int main ()
  {
  init ();  // initialize timers
  Serial.begin (115200);
  Serial.println ("Hello, world");
  Serial.flush (); // let serial printing finish
  }  // end of main

Force library inclusion
If you run with the "empty sketch" concept you still need to include libraries used elsewhere in the project, for example in your main .ino file:
#include <Wire.h>
#include <SPI.h>
#include <EEPROM.h>

This is because the IDE only scans the main file for library usage. Effectively you can consider the main file as a "project" file which nominates which external libraries are in use.

Naming issues

Don't name your main sketch "main.cpp" - the IDE includes its own main.cpp so you will have a duplicate if you do that.
Don't name your .cpp file with the same name as your main .ino file. Since the .ino file effectively becomes a .cpp file this also would give you a name clash.

Declaring a C++-style class in the same, single .ino file (have heard of, but never seen working - is that even possible?);

Yes, this compiles OK:
class foo {
  public:
};

foo bar;

void setup () { }
void loop () { }

However you are probably best off to follow normal practice: Put your declarations in .h files and your definitions (implementations) in .cpp (or .c) files.
Why "probably"?
As my example shows you can put everything together in one file. For larger projects it is better to be more organized. Eventually you get to the stage in a medium to large-size project where you want to separate out things into "black boxes" - that is, a class that does one thing, does it well, is tested, and is self-contained (as far as possible).
If this class is then used in multiple other files in your project this is where the separate .h and .cpp files come into play.

The .h file declares the class - that is, it provides enough detail for other files to know what it does, what functions it has, and how they are called.
The .cpp file defines (implements) the class - that is, it actually provides the functions, and static class members, that make the class do its thing. Since you only want to implement it once, this is in a separate file.
The .h file is what gets included into other files. The .cpp file is compiled once by the IDE to implement the class functions.

Libraries
If you follow this paradigm, then you are ready to move the entire class (the .h and .cpp files) into a library very easily. Then it can be shared between multiple projects. All that is required is to make a folder (eg. myLibrary) and put the .h and .cpp files into it (eg. myLibrary.h and myLibrary.cpp) and then put this folder inside your libraries folder in the folder where your sketches are kept (the sketchbook folder).
Restart the IDE and it now knows about this library. This is really trivially simple, and now you can share this library over multiple projects. I do this a lot.

A bit more detail here.

Nice answer. One most important topic, though, didn't became clear to me yet: why everybody says "you are probably best off to follow normal practice: .h + .cpp"? Why is it better? Why the probably part? And most important: how can I don't do it,  that is, have both interface and implementation (thas is, the whole class code) in the same, single .cpp file? Thank you very much for now! :o)

Added another couple of paragraphs to answer why "probably" you should have separate files.

How do you not do it? Just put them all together as illustrated in my answer, however you may find that the preprocessor works against you. Some perfectly valid C++ class definitions fail if they are put in the main .ino file.

@Spiked3 Is not so much a matter of choosing what I'm most comfortable with, for now, it is a matter of knowing what's available for me to choose from in the first place. How could I make a sensible choice if I don't even know what my options are, and why each option is the way it is? Like I said, I have no previous experience with C++, and it looks like C++ in Arduino might require extra care, as shown in this very answer. But I'm sure eventually I'm getting a grasp of it and get my stuff done without reinventing the wheel (at least I hope so) :)

Thanks for the extra explanation! Now it's a lot clearer to me, and it's working fine with the .h and .cpp files like you explained!

This explaination is better than the arduino build process documentation :-). thanks

I don't know as I haven't used it.

My advice is to stick to the typical C++ way of doing things: separate interface and implementation into .h and .cpp files for each class.
There are a few catches:

you need at least one .ino file - I use a symlink to the .cpp file where I instantiate the classes.
you must provide the callbacks that the Arduino environment expects (setu, loop, etc.)
in some cases you will be surprised by the non-standard weird things that differentiate the Arduino IDE from a normal one, like automatic inclusion of certain libraries, but not others.

Or, you could ditch the Arduino IDE and try with Eclipse.
As i mentioned, some of the things that are supposed to help beginners, tend to come in the way of more experienced developers.

While I feel that separating a sketch into multiple files (tabs or includes) helps everything to be in its own place, I feel like needing to have two files to take care of the same thing (.h and .cpp) is a sort of unnecessary redundancy/duplication. It feels like the class is being defined twice, and everytime I need to change one place, I need to change the other. Note this applies only to simple cases like mine, where there will only be one implementation of a given header, and they are going to be use only once (in a single sketch).

It simplifies the work of the compiler/linker and allows you to have in the .cpp files elements which are not part of the class, but are used in some method.
And in case the class has static memers, you cannot place them in the .h file.

Sure, if the next revision comes up with a way to perform the same tasks that are done by headers, without headers ... but in the meanwhile there are plenty of things that cannot be done without headers: I want to see how distributed compilation could happen without headers and without incurring major overheads.

I'm posting an answer just for completeness, after finding out and testing a way of declaring and implementing a class in the same .cpp file, without using a header. So, regarding the exact phrasing of my question "how many file types do I need to use classes", the present answer uses two files: one .ino with an include, setup and loop, and the .cpp containing the whole (rather minimalistic) class, representing the turning signals of a toy vehicle.
Blinker.ino
#include <TurnSignals.cpp>

TurnSignals turnSignals(2, 4, 8);

void setup() { }

void loop() {
  turnSignals.run();
}

TurnSignals.cpp
#include "Arduino.h"

class TurnSignals
{
    int
        _left,
        _right,
        _buzzer;

    const int
        amberPeriod = 300,

        beepInFrequency = 600,
        beepOutFrequency = 500,
        beepDuration = 20;

    boolean
        lightsOn = false;

    public : TurnSignals(int leftPin, int rightPin, int buzzerPin)
    {
        _left = leftPin;
        _right = rightPin;
        _buzzer = buzzerPin;

        pinMode(_left, OUTPUT);
        pinMode(_right, OUTPUT);
        pinMode(_buzzer, OUTPUT);
    }

    public : void run()
    {
        blinkAll();
    }

    void blinkAll()
    {
        static long lastMillis = 0;
        long currentMillis = millis();
        long elapsed = currentMillis - lastMillis;
        if (elapsed > amberPeriod) {
            if (lightsOn)
                turnLightsOff();
            else
                turnLightsOn();
            lastMillis = currentMillis;
        }
    }

    void turnLightsOn()
    {
        tone(_buzzer, beepInFrequency, beepDuration);
        digitalWrite(_left, HIGH);
        digitalWrite(_right, HIGH);
        lightsOn = true;
    }

    void turnLightsOff()
    {
        tone(_buzzer, beepOutFrequency, beepDuration);
        digitalWrite(_left, LOW);
        digitalWrite(_right, LOW);
        lightsOn = false;
    }
};

This is java-like and slaps the implementation of methods into the declaration of the class. Apart from the reduced readability - the header gives you the declaration of the methods in a concise form - I wonder if more unusual class declarations (like with statics, friends etc) would still work. But most of this example is not really good, because it includes the file only once an inclusion simply concatenates. The real problems start when you include the same file in multiple places and you start getting conflicting object declarations from the linker.


text:
Compiling with -flto and -nostartfiles results in no program at all
Towards developing my own bootloader I've stumbled over an issue with avr-gcc. I am trying to compile my code with the compiler flags
-flto          #to enable link time optimization
-nostartfiles  #to omit the interrupt vector table

My bootloader consists of multiple files which are used depending of compile flags. All the sources are being compiled and linked while the code path only leads to some portions of them. So I wanted to get rid of the dead code and -flto (being a newer development) creates a much smaller machine code size than -ffunction-sections -fdata-sections with -Wl,--gc-sections -Wl,--print-gc-sections.
But when it comes to further reducing the machine code size by removing the interrupt vector table using -nostartfiles, the complete code gets optimized away leaving me with a zero byte output.
Has anyone experienced the same issue with that compiler flag combination?

I have experienced that I couldn't compile an Arduino sketch anymore with LTO because the optmization was so aggressive that it optimized out certain ISRs of hardware peripherals. Maybe GCC thinks that the initial bootup function (at 0x0000 or wherever) is never called and kills everything? Maybe try sprinkling __attribute__ ((used)) over some functions and see what happens? (https://gcc.gnu.org/wiki/LinkTimeOptimizationFAQ)

This is it! It now produces output. But it is not smaller than the --gc-sections version any more. I suppose it was removing some parts already that were supposed to stay. Thank you!

Great to hear! I think I'd be great if you'd answer the question yourself and include your specific critical piece of code that made it work.

As @MaximilanGerhardt wrote in his comment. LTO was optimizing away too much of the code. Usual programs start with the interrupt vector table that in case of a regular reset or startup point to the main function. That is why the compiler knows that main has an entry point and is used. The actual program starts at the table.
Removing  the interrupt vector table with -nostartfiles causes the compiler not to know that main is used at all and optimizes it away.
To give the compiler a hint __attribute__((used)) has to be placed at all methods that have to stay and there is no code path leading to them otherwise.

You've sort of stumbled into something that works, but it's not really the right answer.  What you should be doing is using a linker script (traditionally .ld file) which puts your startup code (preferably a wrapper not main() itself) at the correct address, with a "keep" attribute.   In the case of the AVR the "vectors" are really jump instructions, so if you only want to support the reset one you can probably just start your code there; in other architectures the vectors are pointers, so you'd need the address of your startup code followed by code.

Also note that without startup code, initialized RAM variables won't work, as copying that initialization from flash to RAM is done by startup code; however PROGMEM type values will.


text:
Use photocell as digital input
I need to use multiple photocells as input, but its more than the amount of analog pins that my arduino has.
I'm wondering if theres any way to use a photocell as a digital input, with the photocell triggering at a specific set threshold of light.
It doesn't seem quite possible but I thought I'd ask.

You might like to look at analog multiplexor ICs.  The 4051 is popular. It uses 3 digital lines to select 1 of 8 analogue inputs.  I found a page describing the 4051 on arduino.cc: http://playground.arduino.cc/Learning/4051   I hope this helps. Regards,

I see two possible options for achieving what you want:
Voltage divider
This is the solution proposed by William Roy: you make a voltage divider
circuit and check whether it gives a voltage above the threshold of the
digital input. For example:
+5V ---+
       |
       R
       |
       +--- digital input
       |
      LDR
       |
GND ---+

There are a couple of issues with this approach though:

Every digital input is fitted with a Schmitt trigger which makes
it hysteretic, meaning the voltage threshold for switching from LOW
to HIGH is higher than the threshold for switching from HIGH to
LOW. If the pin voltage is between the two thresholds, it will read
either HIGH or LOW, as determined by the history of that voltage.
Depending on your application, this may not be a problem, and may
even be desirable. But if you want, as you wrote in your question, “a
specific set threshold of light”, it sure will be problematic.

You do not know what those threshold voltages are. The datasheet of
the ATmega328P (the main chip of the Uno) states that
they should “typically” be around 2.1 and 2.6 V, but it only
guarantees that the low threshold should be no less than 1.5 V
and the high threshold no more than 3 V. For any input voltage
between 1.5 and 3 V (which is a very significant range), the
chip manufacturer doesn't guarantee what the pin will read.

The first issue can be solved by using a write-before-read protocol:
first you set the pin to OUTPUT LOW, which will force the input Schmitt
trigger to the LOW state. Then you set it to INPUT and take a reading.
This way you will read HIGH if and only if the pin voltage is above
the high threshold. The low threshold becomes irrelevant. Example code:
/*
 * Read the given pin avoiding the input hysteresis.
 *
 * Returns HIGH if the pin voltage is above the upper (LOW to HIGH)
 * threshold, LOW otherwise.
 *
 * WARNING: The pin is set to OUTPUT LOW for a very short time.
 */
int anhystereticRead(uint8_t pin) {
    pinMode(pin, OUTPUT);
    digitalWrite(pin, LOW);
    pinMode(pin, INPUT);
    return digitalRead(pin);
}

The second point can be solved by calibrating your input using a trimpot
instead of a resistor. You would adjust the pot until the threshold is
exactly what you want. Using fixed resistors instead of a pot will make
it very difficult to achieve your “specific set threshold of light”,
unless you can live with a very rough precision.
Capacitive measurement
The second option is use the LDR as the resistor in an RC circuit, and
measure the charging time of the circuit, like this:
digital output --- LDR ---+--- digital input
                          |
                      capacitor
                          |
                         GND

Starting with a discharged capacitor, you set the output to HIGH and
measure how long it takes for the input to read HIGH. This time is
typically something like 0.73 R C, where R is the
resistance of the LDR and C the capacitance of the capacitor. The
exact numerical factor is not know, as it depends on the high threshold
voltage of the digital pin.
For details and example code, you could check the Capacitance Meter and
RC Time Constants Arduino tutorial, or search the Web for
“Arduino capacitance meter”. You will find material about how to measure
an unknown capacitance using a know resistance, but you can use the same
technique to measure an unknown resistance using a known capacitance.
And you should replace the waiting loop:
while (analogRead(input) < THRESHOLD) {}  // wait

by a similar loop using the digital input threshold:
while (digitalRead(input) == LOW) {}  // wait

The interesting thing about this technique is that you do not need a
trimpot to set the illuminance threshold: you will measure the
charging time and set the threshold in software. Also, this technique is
not affected by the input hysteresis. The main drawback is that the
measurement takes longer than the voltage divider technique.
Edit: I found a blog post describing this exact method in greater
detail: Measuring resistance or voltage with 1 digital I/O,
by Moser.

Yes, you can use LDRs(photocells) as an indirect digital input.
You can design a voltage divider circuit, which incorporates your LDR and gives LOW or HIGH digital readings based on your pre-calibrated threshold light values.
Your voltage divider circuit must reach a specific voltage for your wanted light threshold to give you a HIGH reading.

The following are the voltage thresholds guaranteed to be read as HIGH.

When a pin is configured as an INPUT with pinMode(), and read with
  digitalRead(), the Arduino (Atmega) will report HIGH if:
a voltage greater than 3 volts is present at the pin (5V boards);
a voltage greater than 2 volts is present at the pin (3.3V boards);

Source of Quote

The numbers you quote are not the voltage thresholds: they are the lowest voltages where the pin is guaranteed to be read as high. On the Uno, more than 3 V is HIGH, less than 1.5 V is LOW, anything in between is not guaranteed. The “typical” thresholds are 2.6 V for the LOW → HIGH transition and 2.1 V for HIGH → LOW. These are different thresholds because of the hysteresis introduced by the Schmitt trigger at the inputs.

I'd suggest using a potentiometer, so you can tweak at which light level the pin goes high/low.

You wrote: “Your voltage divider should observe this thresholds”. No, it should not. If it does, then the pin is guaranteed to read HIGH when you expect it to read HIGH (good), but it will also read HIGH across a significant range of voltages where you expect it to read LOW (bad).

LDR in a Wheatstone bridge + OpAmp as a comparator
For more (temperature...) stability of your LDR threshold it could be better to use a wheatstone bridge instead of a simple voltage divider.
Then you can send the output of your wheatstone (or your divider) to a simple OpAmp comparator circuit that will output High or Low, which you can plug in any digital port.
To know more on Wheatstone and OpAmp:
(you can use directly the last schema by plugging the output of the Opamp to the digital pin of your arduino (instead of sending it to the transistor)
http://www.electronics-tutorials.ws/blog/wheatstone-bridge.html
Hope that can help,
Gaetan

authors: Дарина Бакута


text:
Bizarre behavior, loop function affects setup function
I've connected two stepper through two uln2003 chip. And wrote a small class to control them.
The class works perfectly and I'm able to control the steppers (rotate the CW and CCW).
My main code looks like this :
#include "StepperControl.h"

StepperControl myStepperControls[2];

void setup() {
    delay(1000);
    myStepperControls[0].init(6,5,4,3);
    myStepperControls[1].init(11,10,9,8);

    delay(1000);
    for (int i = 0; i < 2; i++)
    {
        myStepperControls[i].DelayBetweenSteps = 1200;
        myStepperControls[i].StepCCWDegree(90);
        myStepperControls[i].StepCWDegree(51);
    }
}
int moveNumber = 0;
void loop(){
    int stepperNumber = moveNumber / 2;
    bool cw = ((moveNumber % 2)  == 0);
    moveNumber = (moveNumber + 1) % 4;
}

As you can see I:

Init both instances of the class to different pins.
Set the Delay between the steps (in microseconds).
Rotate myStepperControls[0] counter clock wise and then clock wise.
Same for myStepperControls[1]

This doesn't work correctly, one of the motors doesn't move clock wise.
It is not always the same motor !! For the last hour the problem appeared only in myStepperControls[0], now it is only in myStepperControls[1].
I'm 100% sure it is not a wiring/electrical problem because:

If I'll delete the content of the loop (which runs after setup) it will fix the problem.
If I'll make the delay between steps 2000 it will fix the problems.
As I've mentioned the problem was only in myStepperControls[0] for an hour, in that hour i switch the pins of the motors and still the motor that was connected to myStepperControls[0] was not able to rotate CW.

Any suggestions to how to investigate the problem will be appriciated
Here is my library code:
// StepperControl.h

#ifndef _STEPPERCONTROL_h
#define _STEPPERCONTROL_h

#if defined(ARDUINO) && ARDUINO >= 100
    #include "arduino.h"
#else
    #include "WProgram.h"
#endif

class StepperControl
{
 public:
    StepperControl();
    void init(byte blue, byte pink, byte yellow, byte orange);
    void StepCW(int steps);
    void StepCCW(int steps);
    void StepCWDegree(float degrees);
    void StepCCWDegree(float degrees);
    const int StepsPerFullRotation = 4076;
    int DelayBetweenSteps;
 private:

    void setPinsState(byte step);

    byte m_currentState;
    byte m_pinValuelookup[9];

    byte m_bluePin; // = 11;    // Blue   - 28BYJ48 pin 1
    byte m_pinkPin; // = 10;    // Pink   - 28BYJ48 pin 2
    byte m_yellowPin; // = 9;    // Yellow - 28BYJ48 pin 3
    byte m_orangePin; // = 8;    // Orange - 28BYJ48 pin 4
                            // Red    - 28BYJ48 pin 5 (VCC)

};

#endif

here is the cpp file :
#include "StepperControl.h"

StepperControl::StepperControl() : m_pinValuelookup{B01000, B01100, B00100, B00110, B00010, B00011, B00001, B01001, B00000}, DelayBetweenSteps(1100), m_currentState(0)
{
}

void StepperControl::init(byte blue, byte pink, byte yellow, byte orange)
{
    m_bluePin = blue;
    m_pinkPin = pink;
    m_yellowPin = yellow;
    m_orangePin = orange;

    pinMode(m_bluePin, OUTPUT);
    pinMode(m_pinkPin, OUTPUT);
    pinMode(m_yellowPin, OUTPUT);
    pinMode(m_orangePin, OUTPUT);
    delayMicroseconds(DelayBetweenSteps);
    setPinsState(8);
    delayMicroseconds(DelayBetweenSteps);
}

void StepperControl::StepCW(int steps)
{
    for(int i = 0; i < steps; i++)
    {
        m_currentState = (m_currentState - 1) % 8;
        setPinsState(m_currentState);
        delayMicroseconds(DelayBetweenSteps);
    }
    setPinsState(8);
}

void StepperControl::StepCCW(int steps)
{
    for(int i = 0; i < steps; i++)
    {
        m_currentState = (m_currentState + 1) % 8;
        setPinsState(m_currentState);
        delayMicroseconds(DelayBetweenSteps);
    }
    setPinsState(8);
}

void StepperControl::StepCWDegree(float degrees)
{
    float steps = degrees * (float)StepsPerFullRotation / 360.0f;
    StepCW((int)steps);
}

void StepperControl::StepCCWDegree(float degrees)
{
    float steps = degrees * (float)StepsPerFullRotation / 360.0f;
    StepCCW((int)steps);
}

void StepperControl::setPinsState(byte step)
{
  digitalWrite(m_bluePin, bitRead(m_pinValuelookup[step], 0));
  digitalWrite(m_pinkPin, bitRead(m_pinValuelookup[step], 1));
  digitalWrite(m_yellowPin, bitRead(m_pinValuelookup[step], 2));
  digitalWrite(m_orangePin, bitRead(m_pinValuelookup[step], 3));
}

Some one helped me in the Arduino forums, and I felt obligated to add the answer here :
The : m_currentState = (m_currentState - 1) % 8; is the bug.
I accidentally assumed that doing % on -1 will jump to 7.
Somehow this caused the strange behavior I had.

You found the solution yourself. I am posting this answer anyway just to
give some background on the problem.
I must say you were somewhat unlucky: you have just hit a couple of the
least intuitive features of the C and C++ languages: integral promotion
and signed division.

Integral promotion: C does not know how to perform arithmetic on
anything smaller than an int. When you write m_currentState - 1,
the variable m_currentState is automatically promoted to int.
Note that this promotion has converted an unsigned type (byte is
unsigned) into a signed integer. Then, (byte) 0 - 1 is (int) -1
instead of (byte) 255.
Signed division: When dividing a negative number by a positive
one, the quotient is rounded towards zero and, conversely, the rest
is negative. Then, -1 % 8 is -1 instead of 7.

There are several ways around these problems. One is to replace the
modulo operation % 8 by a bitwise and: & 7. This is an optimization
the compiler would have done anyway if dealing with unsigned integers.
The option I prefer is to simply undo the integral promotion by an
explicit cast:
m_currentState = (byte) (m_currentState - 1) % 8;

This way, if m_currentState is zero, (byte) (m_currentState - 1) is
255 and the result is, as expected, 7. Also, the compiler optimizes the
unsigned modulo operation into a bitwise and: the whole lines compiles
very efficiently into just two single-cycle instructions:
subi r24, 0x01  ; subtract 1
andi r24, 0x07  ; bitwise and with 7

It is worth noting that nothing of this would have happened if
m_currentState was an unsigned int, as there would have been no
integral promotion in the first place.


text:
How to volunteer for arduino projects?
I have master in electronics and IT. I know various microcontrollers programming in c. I want to volunteer myself to learn for arduino Projects especially for low Level Drivers etc. Can somebody suggest me Websites or way ?

You want to do what? Help other people, or get help from other people? It's unclear what you are asking for.

The Arduino paradigm is based on abstracting the hardware to a few simple function calls.  So many drivers appear simple to the end user (end programmer).
Most go here for a list of libraries (which have already been written) and how to use them.  I believe these libraries are distributed with the Arduino SDK.  To learn more about writing libraries go here. I am not aware of any formal method of submitting Arduino libraries.  If I wanted to find out more I would go here and participate in the forum.  However, using the forums search, I found this specific (several years old) post where it says:

You can add a page to the Playground section:
  http://playground.arduino.cc/ You might start by adding your website
  with Arduino code to the index of the playground, perhaps a page in
  the Playground section is not needed. The index can contain links to
  websites, to the Arduino forum or to a page in the Playground section.
You can not change or add to the reference or official libraries.

Most of the libraries to read sensors like as Dallas/Maxim 1Wire products, or to interface to RF-, WiFi-, and other radios are user-contributed and maintained, and most, if not all, of them are community maintained and on github.
Update:

Is there any official repository for arduino libraries where someone
  can contribute and submit patches?

"Official": I don't think so, at least I don't know of one if there is, but I am also just learning my way around the open sources.
But you'll probably find most of the libraries in github, and they are usually there to share development. They aren't generally grouped as "Arduino", but by each author's github username.
So the best approach is probably to identify the library in your "libraries" folder that you want to update, and its author's name which is usually in the source-code header comments. And, if you get lucky, a URL to the github project. Otherwise go to github and search for the library, using the author's name or a quick comparison of some the source code to be sure you've really found the same library.
(As I am a user & beneficiary of open source code, you have my sincere thanks for choosing to do this! I haven't gotten that far yet; I hope to, soon.)

can I contribute ? Is there any official repository for arduino libraries where someone can contribute and submit patches?


text:
ESP8266 only responds to AT and AT+GMR
I purchased a pack of esp8266 (https://www.amazon.com/gp/product/B00PA3UQNI/) and a usb to serial converter (https://www.amazon.com/gp/product/B01FUA2BBU/) from amazon. I hooked them up and attempted to use the Arduino serial monitor to communicate with the esp8266. Here are the commands I used and the responses I got:
    AT
OK
AT+GMR

+GMR: 7.80.5.0

OK
AT+RST

ERROR

My current setup is (RX on serial -> TX on esp) and (TX on serial-> RX on esp), although I have also tried them swapped. I have tried running the serial monitor at 115200, 57600, and 9600 baud and they all put out the same response. I have tried with both boards. I am currently running the esp8266 off of two AA batteries. All grounds are connected, CH_PD is connected to Vsupply with a 10k resistor, RST is connected to ground with a 3k resistor.
I have not done anything with the firmware and I have not tried any other serial monitor.
Please let me know if there is anything else I can try to get these to work.

Your question is wrong, your ESP is responding to AT+RST, it just doesn't understand what AT+RST means. Have you tried any other documented AT commands?

I have tried AT+CWLAP and AT+CWMODE. Both return ERROR.

Looks like you have some odd (i.e. not the "standard" Espressif) firmware on there. Output of AT+GMR for me is AT version:1.1.0.0(May 11 2016 18:09:56)
SDK version:1.5.4(baaeaebb)
compile time:May 20 2016 15:06:44
OK - though, I have flashed the very latest version of the AT firmware, but you can see it outputs a lot more info than just a version number

Shouldn't flashing ESP8266 again with latest firmware fix your problem? I have this same esp8266 module but I do get proper version info like @jaromanda X


text:
Complex Arduino programs
Im working on a RGB LED matrix project (10 x 10 Neopixels) and I'm using classes to handle the different hardware components. Whats the best way to deal with multiple files in the project eg, I have a class which holds the various display functions such as writing text and drawing circles, but every time I change something it takes ages to compile (Greater than 30 seconds) is there a way to have multiple files without using classes?
Any help would be greatly appreciated.
Cheers

In my experience simply having multiple files should not inflate your compile time by that much. What Arduino are you using? i would try troubleshooting (i.e. what happens when there is 1 file with all your functionality? what happens when there are multiple files with less functionality?)

I'm using sublime with STINO as an instead of the IDE to program a nano v3

You can have multiple files without implementing any classes. just make sure to include the arduino.h header in them if you want to use any arduino API (like "digitalWrite", pinMode, etc..)

Look at the compilation messages. Does it recompile everything when you change a single file? If so, you should probably file an issue.

What version of the IDE and what host (Windows, Linux, etc)? If you are running on Windows you need to shut off the virus scan of generated files.

I'm using windows 10 with the latest version of Arduino. I have added the temp folders in the exception list for avast but its still really slow, I think it could be something to do with the STINO build process

I like to separate logical chunks of a complex program into libraries. The IDE I use (UECIDE) then caches those libraries and it compiles very fast.

I noticed that it is very hard to use classes with the default IDE.
Each file will be in a different tab, but normally each class has a header (.h) and implementation (.c) file, so 2 extra tabs per class.
If you have just 3-4 classes you can use the default IDE.
However, if you want to use more, you have to use e.g. Eclipse or Visual Studio, whatever IDE you like best.
Search for Eclipse/Arduino, I think there are multiple options.
Myself I use visualmicro ... it is free except you cannot use the debugger option.
I used several classes in my sketch and don't think the compile time was 30 seconds; it might be depending also on the amount of include files.
Also a complex program is not necessarily a program with many classes. I would say, that if you put too much functionality in one class (or one single sketch), you get a complex program.

I'm currently using STINO but ill have a look in to other IDE's. Cheers

Yes you can have multiple files without classes.
Functions don't have to go in classes, see loop and setup for an example. All you have to do is declare the function in a header file and then implement it in a body.
so:
// File Bob.h
#ifndef __BOB_H__
#define __BOB_H__

int SomeFunction(const char val);

#endif // __BOB_H__

// File Bob.cpp
#include Bob.h
int SomeFunction(const char val)
{
   return (int)val;
}

// File SketchName.ino
#include "Bob.h"

setup()
{
  ......... Stuff

Now in theory the compiler will only rebuild Bob.cpp when you change code in it.  In practice you will change code in it and the compiler won't rebuild it and you'll tare your hair out until you remember that if all else fails, rebuild all!
In SketchName.ino some people will say you should always put your includes first, some will say last and some will say it makes no difference.  In my experience its easier to fix duplicate definitions by changing your code so I always put 'my' includes last, because that way the compiler will report the errors against my code.
BTW 30 seconds is not a long build time.  I've worked on projects taking 12+ hours, and missing a semi colon on those projects does not make you popular :)

Ahh, this sounds about right. I am using STINO with the full compile option switched on because I'm changing the cpp files quite often. I'll have a go at your suggestion when i get home tonight, cheers.

Sounds recognizable, build times of multiple hours. However, I hope you could check semicolons without having too do a full build. In my work full builds are scheduled at night, so waiting times can be some hours + 8+ hours depending when initiating a full build.

Whats your methodology when working on huge programs, do you have some software for debugging or do you rely on the compiler throwing highlighting the errors?

It depends what the platform is.  For Arduino I extract all the non-platform specific code out and get it compiling in Visual Studio (Community) and then write a set of tests to make sure every function and class does what I expect.  I've also written some mock modules that offer some Arduino functionality (pinMode, digitalWrite, etc) so I can tests lower level code on the PC.  Then switch to the Arduino as late as possible.  The only way (AFAIK) to debug on an Arduino is Serial.Print or similar.


text:
Certain String Characters To Int
I have a char* array which looks like this "T 20" and I'd like to extract the "20" and convert it in to an integer. I was thinking of using atoi() but it seems that function will operate on the entire string, not just the bits I want. Memory is a bit tight so is there a function similar to atoi() which allows you to specify which charters to operate on?

How about
char array[5] = "T 20";
int num = atoi(array+2);

This obviously assumes that all your strings are of the same format "A NN". If not, you can try parsing it using strtok(). See this excellent answer.


text:
ESP 8266-01 Library
I've just bought two of these wifi modules in the hope of setting up some sort of sensor network. Please could somebody recommend a good library for the arduino.
Cheers

Program it direct. If you must use an Arduino with it then use the Arduino as a programmable IO expander.

if you want to program the ESP itself - https://github.com/esp8266/Arduino

You don't need a library.  At the most basic level you fire AT command to it via a serial connection, but that's like using a Ferrari to go grocery shopping once a week.
It has a 80/160MHz processor 10 digital and one analog port (although you got the version where only one digital port is exposed).  You can program it through the Arduino IDE (You need to go to the board manager to download the BSP for it).  Then like Majenko says, it should be talking to the Arduino (over I2C or SPI) and treating the Arduino is the GPIO expander.

the esp01 has 3.5 GPIOs exposed, not just 1; you can drive an rgb led with one...

Thanks @dandavis i always thought the 01/07/12 meant the number of gpios exposed.


text:
Array Addressing
Is it possible to use a name instead of a number to address an array? I was reading about enum lists and thought it might be possible.
ie
int array[3] = {something, somethingElse, somethingMore]
array[second] => somethingElse
I am asking as I have an array looking after flags for several functions and would like to be able to use the function name instead of a number to address the array.
bool flag[6] = {1, 1, 1, 1, 1, 0}; // Power, Jump 3, Jump 7, Fade 3, Fade 7, Pause active

I'm voting to close this question as off-topic because it's a generic programming question.

No, but you can use a struct:
struct flags {
    uint8_t power;
    uint8_t jump3;
    uint8_t jump7;
    .... etc ....
};

struct flags myFlags;

myFlags.power = 1;
if (myFlags.jump3) {
    .... stuff ....
}

Or you can continue to use a simple numeric array and assign names to the numbers, either with #define, const variables, or an enum.
enum flags {
    power, jump3, jump7, fade, fade7, pause
};

bool flag[6] = {1, 1, 1, 1, 1, 0};

flag[power] = 1;
if (flag[jump3]) {
    .... whatever ....
}

That's brilliant thanks, ill give them a go.

Used the struct method, works perfectly :) thanks


text:
pH ORP sensor esp12 esp82666
I need to know if there is a sensor that mesure pH and ORP, I have already googled about this type of sensor but i found only AtlasScientific that commercialise this kind of sensor
thanks

Yes there are lots.  You might try search for "Arduino PH Sensor" and "Arduino ORP sensor" you'll get a lot more hits for Arduino than ESP8226.
This might be useful:
http://www.instructables.com/id/ORP-pH-Temperature-Data-Logger/?ALLSTEPS


text:
Cannot open file with underscores using the SD library
So I'm trying to create a new file that has underscores in its name. However, when I try this, no file is created.
This works
String fileName = "NMEA.txt";
mySensorData = SD.open(fileName.c_str(), FILE_WRITE);

This does not work
String fileName = "NMEA__23_33_3__16_7_29.txt";
mySensorData = SD.open(fileName.c_str(), FILE_WRITE);

Does anyone know why?

[The SD library] uses short 8.3 names for files.

source

Do you have any tips on how I can organize my files then? As you can see in the above format, I have it as NMEA__hr_mn_ss__yr_mm_dd.txt.

I tried String fileName = "/23_33_3/16_7_29/NMEA.txt" to organize it by directory and it doesn't seem to create them.

Have you actually created those directories? It won't magically make them for you...