text:
RGB LED color control with a single value
Apps like Photoshop have a single slider to select color: .
I'd like to achieve the same using variable resistance knob as a slider to control color of RGB LED. Can anyone put me on the right track how to linearly map color values?

Use HSV like Majenko said. But you might also like to look at adding gamma correction to those RGB values. Our eyes don't perceive differences in brightness linearly.

Any advise how to perform this? I was not going to adjust brightness or saturation and just go with max values.

Adafruit has a great explanation and guide for this at https://learn.adafruit.com/led-tricks-gamma-correction/the-issue

Thanks, gamma correction quick fix was so easy to implement and improved the look, especially after implementing pulsing fade

What you are controlling there is one out of three values from the HSV (aka HSB) colour space.
Colour can be represented in a number of different ways, called "spaces".  You computer monitor displays colour in the RGB colour space - red, green and blue. An RGB LED of course also displays in the RGB colour space.  Your colour printer works in the CMYK colour space.
Different colour spaces represent the colour using different values and combinations of values, and which colour space you use may be imposed by technical limitations (such as in the printer it is dictated by the combination of the colours of the inks).
HSV is a convenient way of visually manipulating colour since it gives you easy to understand "Hue" (the colour), "Saturation" (how much colour) and "Value" (or "Brightness" - how light the colour is) values that are easy for a human to understand.
However physical devices don't generally work with that colour space, so you need to be able to translate between them.
You can think of HSV as the "Human" colour space, and RGB as the "Digital" colour space.
Fortunately it's relatively simple to convert from one to another and there are a number of code snippets online that give examples of how to do it.
I'm going to include one here that I use in my chipKIT TFT display library "Cariad".  Given three 8 bit values (0-255) of "hue" "sat" and "val" it will calculate the red, green and blue values. "hue" would be the one you change with your pot - the others can be static values (or you could add more pots to control those too).
    unsigned int H_accent = hue/43;
    unsigned int bottom = ((255 - sat) * val)>>8;
    unsigned int top = val;
    unsigned char rising  = ((top-bottom)  *(hue%43   )  )  /  43  +  bottom;
    unsigned char falling = ((top-bottom)  *(43-hue%43)  )  /  43  +  bottom;

    int r = 0;
    int g = 0;
    int b = 0;

    switch(H_accent) {
        case 0:
                r = top;
                g = rising;
                b = bottom;
        break;

        case 1:
                r = falling;
                g = top;
                b = bottom;
        break;

        case 2:
                r = bottom;
                g = top;
                b = rising;
        break;

        case 3:
                r = bottom;
                g = falling;
                b = top;
        break;

        case 4:
                r = rising;
                g = bottom;
                b = top;
        break;

        case 5:
                r = top;
                g = bottom;
                b = falling;
        break;
    }
    if (r > 255) r = 255;
    if (g > 255) g = 255;
    if (b > 255) b = 255;
    if (r < 0) r = 0;
    if (g < 0) g = 0;
    if (b < 0) b = 0;

What are the ranges for "hue" "sat" and "val" values in this script? Is it 0-128?

0-255 full 8 bit range

Works like a charm. I wander why colors look different while Arduino board is powered via USB and via power supply connection

Because of the varying forward voltages of the three LEDs and the differing incoming supply voltage.


text:
MQ135 output on Arduino Uno
I bought an FC-22 (MQ135) gas sensor module which I plugged into my Arduino Uno. I connected it to the A0 analog port. Then created a code that reads the raw data from A0 (code below).
When I run the code on my Arduino Uno in my house I get values of about 30. If I blow over the sensor I get values until about 160. My question is now how I have to read / interpret these values.
According to the MQ135 specifications the sensor has a sesitivity for air quality, measuring benzene, alcohol and smoke.
How can I interpret the values I get? What is a good value and what isn't? Do I have to calculate something out of these values?
My code looks like this:
void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);
}

void loop() {
  int sensorValue = analogRead(0);
  Serial.print(sensorValue, DEC);
  delay(100);
  if (sensorValue > 50) {
    digitalWrite(13, HIGH);
  }
  else {
    digitalWrite(13, LOW);
  }
}

any reference for co2 calibration?

@manish As for now the only info I have is from the answer below in the datasheet of the MQ135.

According to the datasheet you have to calibrate it.

Thanks for the link to the datasheet. Yep, at the end of the document indeed it says to calibrate the sensor to either 100ppm NH3 or 50ppm Alcohol. Unfortunately, I haven't got the tools to create an atmosphere with these contents. Furthermore, I'd be more interested in CO2 values, even if I didn't state that in the initial question.

@Socrates Any update on CO2? I'm struggling with it. Could you please help me out?

@AdityaPonkshe I haven't got any update on this yes, sorry. Please post it here, if you get it running.

source: Stack Exchange

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

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

sort: votes


text:
Arduino IDE fails without sudo
I use Arduino IDE 1.6.6 on Ubuntu 15.10.
Starting the Arduino IDE without using sudo fails for both:

uploading the code to the Arduino Uno
starting the serial monitor

The group I need to add my user to is called dialout:
myuser@mycomputer:~$ ls -l /dev/ttyACM*
crw-rw---- 1 root dialout 166, 0 Dez 12 17:57 /dev/ttyACM0

So I added myuser to dialout:
sudo usermod -a -G dialout myuser

Somewhere I read that I have to add myuser to tty as well, so I did it:
sudo usermod -a -G tty myuser

Though I still fail with the above mentioned when trying to use the IDE with myuser.
What do I have to do to get the IDE working with myuser?

Have you logged out yet?

@IgnacioVazquez-Abrams Oh, that was it. I had to log off and on again, something I rarely do. I feel so stupid now for not having tried that. Thanks for telling me!

There should be a command like 'id' or something similar that will show the groups you are a member of. Run that to check that the new groups have taken effect – you may need to log out and then log back in.
The other thing to check is the group owner of the device itself (in /dev). that will also need to match the group you assigned to yourself. Also make sure that the device permissions allow group access.

This is a very informal "solution", not too useful for beginners.

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


text:
SIM900 GRPS Shield Power down over issue AT+CIICR cmd(Bring Wireless Coms)
I'm trying to get the TinySine SIM900 GPRS Shield working to get data over the GPRS network, using Arduino MEGA.
I'm Able to register my SIM with this Shield and even , but as soon as I sent the command AT+CIICR to Bring up the Wireless Coms, the Shiled powers down, all LEDs are OFF except the Red one.
What is the source of the Problem?
Thanks

Maybe you could start with showing the code of your sketch so we have a chance to see what might not be correct?

The SIM9000 shield requires up to 2 Amperes to operate its wireless functions. Thus it must be powered from an external 9 Volt power supply, and the supply should be able to supply at least 2 Amperes, preferably more.
The shield will thus not work if powered through the Arduino, or using a low current external supply. The current draw for initial setup is low, hence registration of the SIM might be fine. Enabling wireless pushes the current draw beyond what your supply can cope with. This is shutting your setup down.
Replace (or use) a 2 Amperes or better 9 Volt DC power supply, feed this power to the shield, not the Arduino, and attempt your code again.
Note that there are some changes required in using an Arduino Mega instead of the Uno with the TinySine GPRS shield, which are described in the help files and on some example videos on YouTube.


text:
Pre-heat time required for MQ-5 gas sensor
The datasheet of MQ5 sensor says, it requires a pre-heat of 24 hours. Does this mean that it needs to be powered on for 24 hours consecutively before usage? Some other websites (e.g. http://www.circuitstoday.com/interfacing-mq5-lpg-sensor-to-arduino) say that 15 minutes pre-heat would suffice. Could someone clarify this issue? Thanks.

I used one after a few minutes or heating.

salut , NB que le MQ 5 ne peux tenir que +/- 1 semaine et après il va plus marcher ... car l capteur de gaz est un petit truc qui brûle à l’intérieur et qui va s’arrêter de brûler après cette semaine et donc le capteur ne marchera plus !! Google Translate: > hello, NB that the MQ 5 can only take +/- 1 week and after it will not

work ... because the gas sensor is a little thing that burns inside
and will stop burning after this week and so the sensor will not work
anymore

Does this mean that it needs to be powered on for 24 hours
  consecutively before usage?

No, it just means that typical performance data in the datasheet has been measured after 24h. So, if you want to be within specification you must observe that 24h preheating time.
Does it mean you can't use the sensor before those 24h? Absolutely not. Given the small size of the sensor, thermal equilibrium will be almost surely reached within 30 min. And it would probably take just a few minutes to be within +/- X % of the specification (you can only know by actually measuring how much time does the output need to stabilise, which you should do).
At the end, the time to wait for thermal stabilisation of the sensor (preheating time) will depend on your application.
Only if you want a very accurate measure of gas concentration, you will need to wait those 24h (and also have a good calibration of your sensor, as well as means to compensate other environmental factors like temperature, humidity, etc.). But if you wanted to do this kind of measurement you probably won't be using a MQ-5 sensor anyway.
EDIT:
Take a look at this excellent technical note from Figaro Sensors to better understand the preheating time. It ISN'T a burn-in time per se, but a stabilisation time whose duration depends on several factors.

Please be clear when you mean the one time only pre-heat and when you mean turning the sensor on to take a measurement.
It is a electrochemical sensor and it needs time to burn-in. During those 24 hours, the impedance of the sensor changes a lot. After those 24 hours it can be used in a normal way and it will return consistant values.
The pre-heat should be done just once. I mean: just once in the lifespan of the sensor. After buying it, you should run the pre-heat.
When the manufacturer writes in the datasheet that the pre-heat time is 24 hours, then you should do 24 hours.
I suggest to connect the sensor in a normal way, with 'A' en 'B' pins connected and with the load resistor, and keep it on for 24 hours. Maybe it is already stable after a few hours, but keep it on for 24 hours to be sure.
To take a measurement, the sensor needs time to warm up. About 5 minutes might be okay. I think that 2 minutes is definitely too short.
When the sensor is always at room temperature, and the time to warm up is always the same, then the measurement is relative accurate and can be compared with other measurements. That means that when the sensor is mostly turned off to save power, only a few minutes to warm up can be used. However, I would start with at least 5 minutes.
[EDIT] The datasheets and other information from the manufacturers use the term "pre-heat" in different ways. The Technical Note in the link by @EnricBlanco uses the term "preheating" only for the "one-time-only" heating after storage to make the sensor more stable, as far as I can tell. Although it is not "one-time-only", it should be applied after storage or changing conditions as well. @EnricBlanco, try a very cheap MQ gas sensor (which is probably not preheated in the factory) and see how the impedance changes a lot during the first hours of preheating, and becomes stable after a few hours.


text:
Arduino Nano -- cannot download, no /dev/tty*** device
It appears to me that each Arduino has (should have?) a unique /dev/tty...USB... number assigned. Why this isn't explained anywhere (that I can find) is a mystery. When I plug my problem Nano into a USB port on my iMac no /dev/tty... for it appears. It used to work. Have I fried it? Can this be fixed?

Check in system monitor or whatever they call it for unknown devices - you may have lost the FTDI (or whatever) driver.

Did you select the 'Nano' on the Tools->Board dropdown menu?

Sure. I have successfully programed a Micro and 2 other Nanos.

This is probably a duplicate question and duplicate answer, but ...
Flip the board over, look at the bottom. If it says "FTDI" then this answer doesn't apply. But many cheap clones have moved to the CH340G chip for USB serial communication, it's a tenth of the cost with a tenth of the (unused) features.
You can find CH340/341 drivers from the manufacturer at WCH.CN or linked at the bottom of this post.
Or, skip the USB altogether and search for "ISP" on Tindie and grab a USBASP or TinyISP programmer.

My nano does not say FTDI on the bottom so I loaded the driver. Didn't work. I don't understand the Tindie ref.?

Do you at least get a power LED when you plug that device in? That should work independently. USBASP and TinyISP programmers (among other models) connect to the 2x3 pin header on the side opposite the USB connector and allow one to directly upload code, bypassing USB altogether.

Yes, the power light is on and the led labeled "L" on and off. If the 6 pins bypass USB then how would I access them from my iMac. BTW: I have 3 Arduinos that don't do the USB: old 1 Micro from Ada (FTDI, used to work, I must have fried it, still has power), 2 from Aliexpress @ $2.70 ea. (non-FTDI, poorly soldered pins). BTW: you might be interested in http://dicks-raspberry-pi.blogspot.com/ (my blog). Mostly Rpi but posts 66-68 about Aruino.


text:
Use a 2.8" TFT with my Leonardo
for 2.8" diagonal color touchscreen TFT:
Readme states:
"Works with any classic Arduino '328. Solder closed three jumpers to use the ICSP header for use with Leonardo or Mega"
What should I solder? See image.

The things you should solder are on the TFT - we need a picture of that to point you to the right bit.

Thanks. How would I have guessed? Here's the underside of the TFT.

It looks like that display doesn't have a touch screen, only a tft and sd card. The modifications you would need to make pertain only to the SD card and the nonexistent touch screen interface. The tft portion should work with any arduino since it is a bit banged 8 bit parallel interface.


text:
Atmel Studio and Arduino IDE compiles the same code different
Before going in details I need to say I am trying to program Arduino Nano board with atmega328p.
Here is my code in Atmel Studio;
#include <avr/io.h>
#include <string.h>
#include <avr/interrupt.h>

int received;
int pinState = 0;

ISR(USART_RX_vect)
{
    //cli();
    while(!(UCSR0A&(1<<RXC0))){};
     //clear the USART interrupt
    received = UDR0;
    UDR0 = received;
    //sei();
}

int main(void)
{
    //DDRB |= (1 << PORTB3);
    //DDRD |= (1 << PORTD3);

    DDRD = 0xFF;
    DDRB= 0xFF;

    #define F_CPU 16000000

    TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
    TCCR2B = _BV(CS22);

    TCCR0A |= _BV(WGM00) | _BV(WGM01) | _BV(COM0A1);
    TCCR0B |= _BV(CS02);

    #define USART_BAUDRATE 9600
    #define UBRR_VALUE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)
    UBRR0H = (uint8_t)(UBRR_VALUE>>8);
    UBRR0L = (uint8_t)UBRR_VALUE;
    UCSR0B |= (1 << RXEN0) | (1 << TXEN0) | (1 << RXCIE0);   // Turn on the transmission, reception, and Receive interrupt
    UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);
    //DDRB |= (1 << DDB1)|(1 << DDB2);

    sei();
        while(1)
    {

    }
    return 0;
}

And here is the code in Arduino IDE;
#include <avr/io.h>
#include <string.h>
#include <avr/interrupt.h>

int received;
int pinState = 0;
ISR(USART_RX_vect)
{
    //cli();
    while(!(UCSR0A&(1<<RXC0))){};
     //clear the USART interrupt
    received = UDR0;
    UDR0 = received;
    //sei();
}
void setup() {
 DDRD = 0xFF;
    DDRB= 0xFF;

    #define F_CPU 16000000

    TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
    TCCR2B = _BV(CS22);

    TCCR0A |= _BV(WGM00) | _BV(WGM01) | _BV(COM0A1);
    TCCR0B |= _BV(CS02);

    #define USART_BAUDRATE 9600
    #define UBRR_VALUE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)
    UBRR0H = (uint8_t)(UBRR_VALUE>>8);
    UBRR0L = (uint8_t)UBRR_VALUE;
    UCSR0B |= (1 << RXEN0) | (1 << TXEN0) | (1 << RXCIE0);   // Turn on the transmission, reception, and Receive interrupt
    UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);
    //DDRB |= (1 << DDB1)|(1 << DDB2);

    sei();
}

void loop() {
           // wait for a second
}

As you can see these codes are exactly the same (except the setup-loop format)
Now I am using exact same parameters for AVRdude;
-CF:\arduino-1.0.6\hardware/tools/avr/etc/avrdude.conf -v -v -v -v -patmega328p -carduino -P\.\COM9 -b57600 -D -Uflash:w: and following the hex file that is created after compile. But when I examine the verbose output of avrdude.exe they are different.
Arduino program works but the program uploaded using Atmel Studio does not. For more information everything about avrdude and parameters are working and it uploads and doesnt give any errors.
I chose atmega328p in Atmel Studio which is correct because I am using arduino nano board.

In arduino the init function is called

Just to help identify the problem: try to put the Atmel Studio version in the Arduino IDE. In principle you do not need to use the setup-loop format in Arduino: you can provide your own main(), and it will override the one from libcore.

I found the solution (or what the problem is). Avrdude not only requires MCU model but also programmer parameter. If you are using any of Arduino based boards you need to add -c programmer id do avrdude input parameters.


text:
AVR Timer1 OCR1A controls TIMER1_COMPB_vect interrupt!
I was struggling with timer interrupts in my project. I couldn't make it work properly. So I decided writing a simple code and I saw a very interesting case.
ISR(TIMER1_COMPB_vect)
{
        PORTB ^= (1 << PORTB5);
}

int main(void)
{
    cli();          // disable global interrupts
    TCCR1A = 0;     // set entire TCCR1A register to 0
    TCCR1B = 0;     // same for TCCR1B

    OCR1A = 10000;
    OCR1B = 100;

    TCCR1B |= (1 << WGM12);

    TCCR1B |= (1 << CS10);
    TCCR1B |= (1 << CS12);

    TIMSK1 |= (1 << OCIE1A);
    TIMSK1 |= (1 << OCIE1B);
    DDRB= 0xFF;

    #define F_CPU 16000000
    sei();
    while (1)
    {

    }
}

Here is my code. When I change OCR1B value, nothing happens, but if I change OCR1A value then blinking gets faster. Is there a logical explanation for this?

@Gerben No. OCR1A is 2 byte. OCR1AH and OCR1AL are single byte.

By setting WGM12, you set the time to CTC mode. In this mode the timer will restart when it reaches that value set to OCR1A. So the lower the value, the faster it restarts, so the higher the frequency.
The OCR1B value only changes where in this cycle the interrupt occurs. It will however still only be called once per timer1 overflow.

Short but very clear explanation. respect

Thanks. Timers are a bit hard to understand, but very powerful.


text:
In system programming for avr?
I generally use sockets for AVRs in standalone circuits, but sometimes I sell my items and therefore I soldier the chip on the circuit. As you guess I can upgrade the code inside the chip with socket simply putting the chip out and putting it into the programmer board, but It doesn't work the same way with the ones which are soldiered on the circuit.
I know there are some ISP devices like USBtinyISP etc., but I want to be more professional and know exactly how an in system programmer work.
Do I have to use Avrdude If I design my own In system programmer? Isn't there any way that is more universal?
I searched the internet for a long time and I found only hobbyist stuff. Can anyone explain or simply direct me to a good source that explains this topic? Thank you in advance.

You can still use the Arduino IDE. Just change the "programmer" in the menu. Just add a ISP header to your project.

ISP works by using a serial connection (usually via the SPI and nRESET pins) to the MCU. The programmer talks to the device using the low-level protocol that the device expects, and connects to the host using a different, high-level protocol. The host then directs the programmer to perform the various programming actions on the device, and in turn the programmer reports to the host about its current status.
There are a number of programming protocols that already exist, such as the one described in AVR910. As long as both the connection type and the protocol itself are supported by AVRDUDE it will work transparently once the hardware is assembled.
Further details about ISP are available in both AVR910 as well as the "Serial Programming" section of the datasheet for the device in question.

You can use an ISP using the Arduino UI - simply select your programmer (tools->programmer) then "upload using programmer" (under the file menu).
Alternatively, you could use a pre-programmed AVR to do the programming - see http://www.atmel.com/images/doc0943.pdf for the spec. I think an AtTiny would be enough, depending on how big your program is, you might need some external storage. You could set it up with a "read" and a "write" option, so you program your dev AVR normally, then use an AtTiny to suck the data off, then push it up to one of the others. This is left as an exercise to the reader.
In any case, you would just need access to the 6 pins - VCC(power), GND(ground), RST(reset), SCK(clock), MISO(master->slave) and MOSI (slave->master). Note that the RST pin has to go high/low at specific times during the programming, so if programming from another AVR, it will need to be a data pin.


text:
Program button to switch between two values
There is a function on one of my programs I want to be switch on and off by pressing a button. The button is unbiased otherwise I would set the function to read the button's status of HIGH or LOW.
So I need to create variable named "switch" with an initial value of 0. Then I would create a function would read if buttonPin is HIGH change the value of "switch" by +1. Next time the buttonPin is HIGH change the value by -1 so that every time the button is pressed the value of "switch" alternates between 1 and 0. Now before my loop calls the function I want on or off it can compare the value of "switch" and run or not run the function.
I don't know how to express this in the Arduino sketch. I'm am also open to alternate ways of achieving the same result.

Pseudocode:
value = 0
if button is pressed:
  value = 1 - value

So simple! I'm almost embarrassed I didn't think of it myself.

Be aware that you will need to debounce the input pin, otherwise you will get erratic results due to the mechanical bounce of the contacts.

So that means I will need to set it back to low with digitalWrite(pin,LOW)?

No, that means that you will have to use the method in the Debounce example to detect button presses if your button isn't already debounced.

Would a pull down resistor have the same function?

No, it would not.

It sounds like you are using a number as a boolean (true/false) value.
You might consider using a a boolean instead.
boolean value = false;
if button is pressed {
    value=!value
}
if value {
    // do something here.
}

You can set it to true or false, or change it to it's opposite (with value=!value as shown above). You can also do if value or if !value ("if not value") - these are equivalent to if value=true or if value=false.

Thank you for the suggestion. I was not aware of the Boolean option.

int buttonPin = 10;
`boolean value = false;
void setup(){
pinMode(buttonPin, INPUT);
Serial.begin (9600);
}
void loop(){
if (digitalRead(buttonPin) == HIGH) {
value=!value;
}
Serial.println(value);
delay(10);
}`
I am using this code. The readout on the serial.Print still reads 0 even if I press the button. I have installed a LED to make sure the button is working and the light turns on whenever I press the button.

The code you gave, just looking at it quickly, should turn value on and off every 10 milliseconds while you press the button. What happens if you move the println inside the if() statement?


text:
How does this code move the bird sprite in this sketch?
I'm teaching this sketch in my class. I understand most of the sketch and can see the class that makes the bird move, but I still don't quite understand how the code makes the sprite "move." I can also see what generates the Pipes but I don't how the code creates them or randomizes them.
Here is the code for both:
Bird
class Chym {

private:
  int frameCount;
  int x;
  int y;
  int deltaIde;
  int delayFrame;

  int jumpCount;
  int maxJumpCount;
  int moveSpeed;

  bool _isDead;
public:
  void respawn() {
    x = 24;
    y = 20;
    deltaIde = -1;
    moveSpeed = 1;
    jumpCount = 0;
    _isDead = false;
  }

  Chym() {
    frameCount = 0;
    delayFrame = 0;
    maxJumpCount = 20;
    respawn();
  }

  void render() {
    if (frameCount < ANIM_FRAME / 2) {
      display.drawBitmap(x, y, flappybird_frame_1, 16, 12, 1);
    }
    else {
      display.drawBitmap(x, y, flappybird_frame_2, 16, 12, 1);
    }
  }

  void update() {
    delayFrame++;
    if (delayFrame == DELAY_FRAME) {
      y += deltaIde * moveSpeed;
      delayFrame = 0;
    }

    if (y > 35) {
      _isDead = true;
    }

    frameCount++;
    if (frameCount >= ANIM_FRAME) frameCount = 0;
  }

  bool isDead() {
    return _isDead;
  }

  void die() {
    _isDead = true;
  }

  void cancelJump() {
    jumpCount = 0;
    flyDown();
  }

  void flyUp() {
    if (jumpCount < maxJumpCount) {
      deltaIde = -1;
      moveSpeed = 3;
      jumpCount++;
    }
    else {
      flyDown();
    }
  }

  void flyDown() {
    deltaIde = 1;
    moveSpeed = 1;
  }

  int getX() {
    return x;
  }

  int getY() {
    return y;
  }

};

Pipe
class Bar {

private:
  int x;
  int y;
  int delayFrame;
  int moveSpeed;
public:
  Bar() {
    delayFrame = 0;
    x = 0; y = 24;
    moveSpeed = 2;
  }

  void setPos(int sx, int sy) {
    x = sx; y = sy;
  }

  void render() {
    display.drawBitmap(x, y - 30, bar_top, 8, 20, 1);
    display.drawBitmap(x, y + 10, bar_bottom, 8, 20, 1);
  }

  void update() {
    delayFrame++;
    if (delayFrame == DELAY_FRAME) {

      x -= moveSpeed;
      if (x < -10) x = 95;

      delayFrame = 0;
    }
  }

  int hitTest(int tx, int ty) {
    int hitX = ((tx >= x - 16) && (tx <= x))?1:0;
    int hitY = ((ty <= (y - 10)) || (ty + 12 >= y + 10))?1:0;
    if (hitX != 0) {
      return hitY;
    }
    return 0;
  }

};

https://www.youtube.com/watch?v=04cY78Y2d3g

This part of your code is what changes the sprite's y-value.
y += deltaIde * moveSpeed;

When you click the "jump" button or when the bird falls the y-value is changed to reflect either an upward movement or a downward movement. When your render() method is called the bird will either be drawn higher up on the y-axis (it's flying) or lower on the y-axis (it's falling).
As for the bars, if you watch closely in the video you can see that they aren't actually randomized.
Compound Assignment Operators
+= is the "plus assign" operator. It adds whatever is on the right side to the variable on the left side. Here is a table of other compound assignment operators: https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Compound_assignment_operators
int x = 5;
x += 2; // equals 7; equivalent to x = x + 2;
x = 5;
x = x + 2; // also equals 7; equivalent to x += 2;

What does the += mean?

@GabeRuiz, it was said in the same post:"x += 2; // equals 7; equivalent to x = x + 2;"

@Avamander if you'll notice the post was edited after my comment to include the answer to my second question, but thank you for pointing it out.

@Chris, thank you for the link. It has helped a lot.


text:
Don't pee there! Device
I want to make a device with a sensor I can attach to the places my dog likes to mark. When sensor becomes wet I want a buzzer to make a loud noise to scare the animal and notify me I need to encourage the dog to go outside. Any suggestions on what sensor to use.

rain sensor.

You probably will want a moisture sensor like this one (there are many variations of this).
This will return one signal when dry, and another when wet.
You will need a Buzzer to make a sound as well (Or a piezo speaker if you feel like getting more advanced) in order to make a sound.
Your sketch should have, in its loop, an if statement checking if the moisture sensor has returned the wet signal (The signal will depend on the sensor you get) and, in the block that executes if there is a signal, a statement driving the buzzer and a delay before turning it off.
Bear in mind that you want to keep the Arduino itself away from the moisture sensor, as your Arduino probably won't survive the dog's doings.


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:
Touch the Neopixels
I want to create a game using the individual LED "pixels" in a Neopixels 8x8 panel as a game pieces. Any ideas how I could add a touch event to each pixel?

Use a trellis.
Or put a resistive touch panel on top of the neopixels. You can connect those using 2 analog and 2 digital pins.

Trellis can only use single color LEDs. I will look into resistive touch panel.


text:
Broken Score on Game Sketch
I have modified the code for Flappy Duino to give me a score at the end of the game. Here is the code:
#include <SPI.h>
#include <Adafruit_GFX.h>
#include <Adafruit_PCD8544.h>

Adafruit_PCD8544 display = Adafruit_PCD8544(7, 6, 5, 4, 3);

#include "Sprite.h"
#include "Chym.h"
#include "Bar.h"

Chym player;
Bar bar; Bar bar2;
int gameScore = 0;
int highScore = 0;
int KNOCK_PIN = 2;
int LED_PIN = 8;

boolean clicked = false;

void loop(){}

void resetGame() {
  player.respawn();
  bar.setPos(0, 20);
  bar2.setPos(50, 30);
  gameScore = 0;
}

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

  display.begin();
  display.setContrast(50);
  display.clearDisplay();
  display.display();

  digitalWrite(LED_PIN, HIGH);

  pinMode(KNOCK_PIN, INPUT_PULLUP);
  pinMode(LED_PIN, OUTPUT);

  resetGame();

  while(1) {
    getInput();
    player.update();
    bar.update(); bar2.update();
    drawLCD();
  }
}

void getInput() {
  int knock = digitalRead(KNOCK_PIN);
  if (knock == 0) { // push down
    clicked = true;
    gameScore = gameScore + 1;
    Serial.println(gameScore);
  }
  else {
    clicked = false;
  }
}

void drawLCD() {
  display.clearDisplay();

  if (!player.isDead()) {
    int ht1 = bar.hitTest(player.getX(), player.getY());
    int ht2 = bar2.hitTest(player.getX(), player.getY());
    int die = ht1 + ht2;
    if (die == 1) {
        // game over
        player.die();
    }

    if (clicked) {
      player.flyUp();
    }
    else {
      player.cancelJump();
    }
    player.render();

    bar.render(); bar2.render();
  }
  else {
    if (gameScore >> highScore) {
      highScore = gameScore;
    }
    display.setCursor(0, 0);
    display.setTextSize(1);
    display.print("ur Score- ");
    display.println(gameScore);
    display.print("HI Score- ");
    display.println(highScore);
    if (clicked) {
      resetGame();
    }
  }

  display.display();
}

The first time the game runs thru the gameScore is greater than highScore so gameScore and highScore print as the same. However every other time the function is called up the highScore doesn't change even when the following statement is true:
if (gameScore >> highScore) {
          highScore = gameScore;
        }

What am I doing wrong?

if (gameScore >> highScore)

You have the wrong operator there.  >> is right shift, so you are right shifting the gameScore by highScore bits, which if it's more than 16 will end up as 0.
Instead you just want > for greater than:
if (gameScore > highScore)

Does the same apply to operators such as ||, &&, ==? Could I have used >=?

Full list of operators: http://www.tutorialspoint.com/cprogramming/c_operators.htm


text:
How Add Piezo Buzz to Pong Sketch
I am junior high teacher teaching students how to program using Arduino. I know the basics of programing but the students wanted to program a game which is a little above my skill set. I am using the following sketch (http://www.itopen.it/arduino-pong-with-8x8-led-matrix-and-max7219/) to introduce them to programing games. Thanks to this site I understand most of the code. However I would like to add a line of code that will make a piezo buzzer buzz every time the "ball" hits the pad. I think the code should look something like the code bellow, but I am not sure if it is correct or where I would put it.
#define buz 8 // number of pin buzzer connected to
     if (HIT_CENTER || HIT_RIGHT || HIT_LEFT) {
        digitalWrite(buz, HIGH);
        delay(100);
        digiralWrite(buz, LOW);
        }

Any help would be appreciated.

The condition HIT_CENTER || HIT_RIGHT || HIT_LEFT will always be true.  (All three of those HIT_ values are non-zero constants.)
Instead, you need to test if getHit() is non-zero.  (To see this, search the sketch for occurrences of HIT_RIGHT or HIT_LEFT.)
The sketch sets up an event timer (via ball_timer = timer.every(BALL_DELAY, moveBall); in setup()) so that ball position will update every 200 ms.  The loop() sequence is: Use timer.update() to service timer events.  Use setPad() to read the paddle position.  Use drawGame() to update the game picture. Somehow use checkLoose() to see if game is over.  Use delay(GAME_DELAY) to wait 10 ms.
Given that structure of loop(), throwing in a 100 ms delay to wait for a buzzer would mess up the game play.  You could turn on the buzzer and set up a timer event for turning it off, each time the ball hits the paddle.
More straightforwardly, since a 10 ms beep is likely to be adequately long, you could test for a hit just before delay(GAME_DELAY), and always turn the buzzer off just after that delay.  In other words, before the delay say:
if (getHit()) digitalWrite(buz, HIGH); and after the delay say digitalWrite(buz, LOW);.
This supposes that writing HIGH to buz turns on the buzzer and that writing LOW turns it off.

Method 1:
here is what i would have done is use this code snippet we can get the state of HIT,,,if it is not equal to HIT_NONE ,buzz it
 #define buz 8
 if(getHit()!=HIT_NONE){
    digitalWrite(buz, HIGH);
    delay(10);
    digitalWrite(buz, LOW);
    }

This is the simpler version where in delay is small,Beaware using delay will completely halt processor operation ,buttons ,joystick serial ports etc everything will be halted.
Method 2:With Flexible Delay
  #define buz 8
  unsigned long previousMillis = 0;
  const long interval = 200;   /////Specify the delay you want here
  void loop()
   {
     unsigned long currentMillis = millis();  //start timer
     /*
         Remaining Code Is Left As It Is
     */
   }

       ///////////Code Snippet Without Using Delay
   if(getHit()!=HIT_NONE){
   digitalWrite(buz, HIGH);
   if (currentMillis - previousMillis >= interval)
        {
            previousMillis = currentMillis;
            digitalWrite(buz, LOW);
        }
   }

But where to add these functions???
Use getHit() to implement ,,,just like below
  int getHit() {
  if(yball != 6 || xball < xpad || xball > xpad + PADSIZE){
    return HIT_NONE;          //returns in case of hit failure so no
                              // buzzer ring
     }
        digitalWrite(buz, HIGH);    //If it has not returned yet makes
        delay(10);                  //sure that it is a successful hit
        digitalWrite(buz, LOW);     //buzzer ring
  if(xball == xpad + PADSIZE / 2){
    return HIT_CENTER;
     }
   return xball < xpad + PADSIZE / 2 ? HIT_LEFT : HIT_RIGHT;
 }

yet again u can replace those 3 lines with below one to be more flexible
digitalWrite(buz, HIGH);
if (currentMillis - previousMillis >= interval)
     {
         previousMillis = currentMillis;
         digitalWrite(buz, LOW);
     }
}

hope this helps.


text:
Student Code: map function not functioning
We made this code in class:
 int red = 6;
  int green = 7;
  int blue = 8;
  int pot = A0;
  int potVal = 0;
  int chosenColor = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(red, OUTPUT);
  pinMode(green, OUTPUT);
  pinMode(blue, OUTPUT);
  pinMode(pot, INPUT);
  Serial.begin (9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  potVal = analogRead(pot);
  chosenColor = map(potVal, 0, 1023, 1, 3);
  if(chosenColor = 1) {
    redCycle();
  }

  else {
    analogWrite(red,255);
  }

  if(chosenColor = 2) {
    greenCycle();
  }

  else {
    analogWrite(green,255);
  }

  if(chosenColor = 3) {
    blueCycle();
  }

  else {
    analogWrite(blue,255);
  }
  Serial.println(chosenColor);
  Serial.println(potVal);
  delay(500);
}

void redCycle() {
    analogWrite(red,0);
  for(int i=0; i < 256; i+=5) {
    analogWrite(red, i);
  }
}

void greenCycle() {
  analogWrite(green,0);
  for(int i=0; i < 256; i+=5) {
    analogWrite(green, i);
  }
}

void blueCycle() {
  analogWrite(blue,0);
  for(int i=0; i < 256; i+=5) {
    analogWrite(blue, i);
  }
}

When we open the serial monitor we find that chosenColor is always 3 regardless of what the potVal is reading. I am sure is something simple but we can't find where is the error. Please help.

analogWrite() doesn't work on pins 7 and 8, only on those bearing the "~" symbol.

Ok that is one problem we didn't think about! Thank you. Still not sure why the map function is not working.

chosenColor = 3 means “let chosenColor take the value 3”.

As Edgar Bonet pointed out,  “chosenColor = 3 means 'let chosenColor take the value 3'”.  That is, your  potVal = analogRead(pot);  chosenColor = map(potVal, 0, 1023, 1, 3); sequence may very well be working, but by the time you get to Serial.println(chosenColor); you have changed chosenColor to 3.
First, the statement if(chosenColor = 1) {...} changes chosenColor to 1. Then the statement if(chosenColor = 2) {...} changes chosenColor to 2.  Finally, if(chosenColor = 3) {...} changes chosenColor to 3, just before you print out the current value of chosenColor.
When you wish to compare two numeric values for equality, use == instead of =.

Aha! I get it. So I need to use ==. We will change that.

You are confusing = (assign) with == (compare).
eg.
Wrong! ...
if (chosenColor = 3)  // this assigns 3 to chosenColor

Correct:
if (chosenColor == 3)   // compare

Still not sure why the map function is not working.

You just assumed it is not working. Before making assumptions like this do a Serial print to show what the return value of the map function is. (Directly after calling map - not later on in the code).

I thought that <= would mean less or equal than. How would I do a greater than or equal to?

<= reads "less than or equal to"; >= is "greater than or equal to".

Not sure if this helps but I wanted a slider with a range of 0 to 200 to give 3 values; 0 for the first third of movement, 1 for the second third and 2 for the last third
I used map(slider value, 0, 134, 0, 2)

Although not related to your main problem, I would like to point out
that there is an issue with your use of the map() function. Or maybe
I should say, with the map() function itself. Since it works with
integer arithmetic, and integer division by default rounds towards zero,
you get a mapping that may be quite different from what you expect.
In the table below, I am showing the result of
map(potVal, 0, 1023, 1, 3). The column labeled “not rounded” is what
you would get if the mapping was done in floating point. The last column
is the rounded value you actually get out of map():
potVal  not rounded  rounded
----------------------------
    0     1.00000       1
            ...
  511     1.99902       1
  512     2.00098       2
            ...
 1022     2.99804       2
 1023     3.00000       3

As you see, you have 512 possible values of potVal mapped
to 1, 511 values mapped to 2 and one single value mapped
to 3.
I assume you would rather have one third of the range mapped to each
value. This can be achieved by writing map(potVal, 0, 1024, 1, 4):
potVal  not rounded  rounded
----------------------------
    0     1.00000       1
            ...
  341     1.99902       1
  342     2.00195       2
            ...
  682     2.99805       2
  683     3.00098       3
            ...
 1023     3.99707       3

This gives 342 values mapped to 1, 341 values mapped
to 2 and 341 values mapped to 3. Now, the problem is that
this way of using map() is confusing. You may prefer to write
something more explicit instead, like:
if (potval < 1023/3) chosenColor = 1;
else if (potval < 1023*2/3) chosenColor = 2;
else chosenColor = 3;


text:
Enternal Analog Reference mode not compiling in Arduino + Intel Galileo Gen 2
I am trying to use external voltage reference in Intel Galileo gen 2 operating in Arduino mode.
So I created a setup code like this:
void setup() {
  // We'll send debugging information via the Serial monitor
  Serial.begin(9600);

  // If you want to set the aref to something other than 5v
  analogReference(EXTERNAL); // use AREF for reference voltage
}

I selected the board as Intel Galileo Gen 2 in Tools option. When I compiled I am getting the following error:
LM35_temp_sensor.ino:21:19: error: 'EXTERNAL' was not declared in this scope

But when I change the board to Arduino Uno in Tools option, the program in compiling fine.
This means that Intel Galileo Gen 2 does not support external analog voltage reference?

There is no such thing as an external analog reference on the Galileo.  If you look at the block diagram that is on the Galiley Arduino.cc page you can clearly see that the Aref pin goes nowhere:

So no, it won't support the EXTERNAL analog reference function.


text:
using more than 8 temperature probe of DS18B20 on Arduino
I am trying to use more than 8 temperature DS18b20 on one bus. Is there any problem to make it work?

As far as I can see there is no limit on the number of sensors you can have on a bus.
So if you are having problems does your code work with less sensors? Try one and work up.
Is it a current issue are you pulling to much from the board?
Is the problem with the one wire library?
Have you got 4.7k pull ups on each sensor?

Is it possible that sharing the VCC is causing interference between the probes data lines do you need diodes after the resistors?

As long as you connect each sensor on a different pin, you should be able to collect the data without any problems.
Otherwise try to search for a I2C temperature sensor and use a demux to control 8 sensors.

DS18b20 uses OneWire, so you can have multiple on the same bus/pin.

It depends on the different address, so he is better of to use an individual pin each time

Each device has a unique 64-bit address. I don't think they made eighteen quintillion units yet, so they don't to have to reuse addresses.


text:
Algorithms to reduce measurement error from analogue sensors
When reading analogue sensors - e.g. load cells, accelerometers - via a microcontroller's Analogue to Digital Converter, there are many sources of potential measurement error including:
a) Warm-up time for electronics
b) Mechanical inertia and resonance
c) Spurious random readings (due to e.g. vibration, electrical interference).
My current software hack for a) and b) is to simply add a suitable time delay before reading the sensors; however there must be a more robust way of detecting and screening for resonance...
My hack for c) is to take the mean of a given number of consecutive readings, but discard any individual readings which exceed a given percentage range from the current mean (pseudocode example below). The trouble with this approach is that it requires an inital `baseline' sensor reading, and if this happens to be spuriously high or low, it can cause subsequent correct readings to be rejected.
Another approach might incorporate a weighted moving average, but this would still be skewed by spurious random readings.
Are there any robust and elegant approaches / algorithms for the above which are commonly applied in commercial devices (e.g. domestic or laboratory weighing scales) that I could include in my code to improve the accuracy and reliability of measurements?
Many thanks in anticipation
// Take mean of multiple sensor readings excluding outliers:

# define SAMPLES 100 // number of samples to take mean of
# define TOLERANCE 0.1 // % range of allowable deviation
                       //between current mean and new values, expressed as decimal

n = 1; // loop variable
total = analogRead(analogPin); // Running total for calculation of mean & baseline reading
mean = total; // mean of all current data

while (n < SAMPLES) {
    new = analogRead(analogPin);
    if (new < (1 + TOLERANCE) * mean) and (new > (1 - TOLERANCE) * mean){
        total += new; // if new reading is within range, calculate new mean
        n += 1;
        mean = total / n;
        }
    // (else ignore new reading)
}
Serial.print mean;

You might want to investigate Standard Deviation and similar statistical models: https://en.wikipedia.org/wiki/Standard_deviation

Thanks Majenko - I'm aware of use of SD in statistical analysis of data.   Is this used in commercial algorithms for reading sensors with microcontrollers in real time though?

I use something very similar to what you are proposing to measure RSSI in an antenna pattern generator.  Say you have an array of 16 samples.  You start filling the array with samples but don't actually output a result until the array is full.  This will give you a startup period of 16 samples where no decisions are made.
After the array is loaded, set a semaphore that indicates that results may now be used to make decisions.  New samples overwrite the oldest sample in a recirculating buffer.  You will now get decision outputs at the same rate as the sample rate with a lag, i.e. when the inputs go to zero abruptly, it will take 16 sample periods for the output to catch up.  I call this a 16 sample rolling average.
For relatively stable inputs, simply take the mean of the array and output that result.
For inputs that are glitchy such as RSSI take the mean of the array and then find the sample(s) that is (are) the farthest away from that mean.  You then recalculate the mean without that sample included.  Note:  Do not discard that sample, simply ignore it for that cycle.  I call this a 15/1 outlyer average.  For my RSSI measurements, this gives me the equivalent of a 48 sample rolling average.  You can do an 8/1, 16/2 system etc requiring 9 and 18 samples per sample respectively, tuning the counts to your particular application.  I am able to get nearly anaechoic chamber results in the middle of a radio noisy office.
Again, note that the outlyers are NEVER discarded as they may represent a real trend.

... and here's my minimal working example for the Arduino. Feel free to adapt it for your own requirements, and please post any improvements or corrections to my script; or any alternative algorithms for the above.
Just noticed that my approach of using the SD to define and exclude outliers is a little more (? unnecessarily) complex than John's algorithm, which defines outliers in terms of the highest and lowest values from the mean; but both methods seem to work nicely.
Cheers!
#define BUFFER 5 // Buffer size (number of readings to use in rolling Mean)
#define SENSORPIN 3 // Analogue input pin from sensor
int data[BUFFER]; // Make an array of appropriate size for Buffer

void setup() {
  pinMode(SENSORPIN, INPUT);

  // Fill buffer with initial data
  int n = 0;
  while (n < BUFFER) {
    data[n] = analogRead(SENSORPIN);
    n++;
  }
}

void loop() {
  // Calculate Raw Mean & SD
  float datasum = 0;
  float diffsum = 0;
  for (int n = 0; n < BUFFER; n++) {
    datasum += data[n];
  }
  float mean = float(datasum / BUFFER);
  for (int n = 0; n < BUFFER; n++) {
    diffsum += ((data[n] - mean) * (data[n] - mean));
  }
  float sd = sqrt(diffsum / (BUFFER - 1));

  // Recalculate Corrected Mean only using data within range +/- 1SD of Raw Mean
  if (sd != 0) {      // Avoid divide by zero error if sd = 0
    float newSum = 0; // Sum of readings within acceptable range
    float newLen = 0; // Number of readings within acceptable range
    int n = 0;
    while (n < BUFFER) {
      if ((data[n] < (mean + sd)) and (data[n] > (mean - sd))) {
        newSum += data[n];
        newLen ++;
      }
      n++;
    }
    mean = newSum / newLen; // Corrected Mean
  }

  // Add your code here to do stuff with variable float 'mean' = the (Corrected) Mean

  // Read new sensor reading, append to buffer and delete oldest reading
  for (int n = (BUFFER - 1); n > 0; n--) {
    data[n] = data[n - 1];
  }
  data[0] = analogRead(SENSORPIN);
}

Thank you John! Your solution is what I was looking for: it resolves my conflict between preserving all the data and excluding the skewing effects of outliers; is simple enough to implement on a microcontroller; and seems to work perfectly. I'm guessing that the rolling mean will also smooth out any potential swings due to mechanical resonance.
I know this is an Arduino forum, but I find it quicker and easier to write interactive code in Python, so I've written a crude `test bed' implementation of your algorithm in Python so that I could get a feel for how it works in practice, with user keyboard input simulating real-life sensor readings. I've avoided any libraries or esoteric Python syntax, so this should be easy to adapt to C++/Arduino. I'm posting it here in case it is of interest to the community.
I've used the formula for Sample Std Deviation (n-1) rather than Population SD (n) which I think is correct in this context, but please let me know if not:
in LaTeX: $SD=\sqrt{\frac{\sum_{(i=1)}^{n}(x_{i}-\bar{x})^{2}}{n-1}}$
If there are any other algorithms or solutions to my post, I'd be very interested to know. Thanks again.
#===================================================
def SampleSD(data,bufLen):
    datasum = 0.0 # NB declare as float to prevent integer rounding error
    diffsum = 0.0 # NB declare as float to prevent integer rounding error
    for m in range (0,bufLen):
        datasum += data[m]
    mean = datasum / bufLen
    for m in range (0,bufLen):
        diffsum += (data[m] - mean) ** 2
    sd = (diffsum /(bufLen-1)) ** 0.5
    print "n: %d\tSum: %f\tMean: %f\tSD: %f" %(bufLen,datasum,mean,sd)
    return mean,sd

#=====================================
def addData(data,bufLen):
    print "\n------------------------------"
    new = input ("Sensor reading: ")
    for m in range(bufLen-1,0,-1):
        data[m]=data[m-1]
    data[0]=new
    return data

#======================================
bufLen = input ("Buffer Length: ")
print
data = [0] * bufLen # Declare an array of suitable length in Python
n = 0

# Fill buffer with initial data
while n < (bufLen):
    new = input ("Initial sensor reading: ")
    data[n] = new
    n +=1
print "\nBuffer initialised."
print "Data: ",data

while True:
    addData(data,bufLen)
    print "Data: ", data
    mean,sd = SampleSD(data,bufLen)
#===========================================
# Recalculate Mean only using data within range +/- 1 SD of mean
    if sd != 0: # Error trap to avoid divide by zero error if sd = 0
        print "\nChecking for outliers:"
        newSum = 0.0 # NB declare as float to prevent integer rounding error
        newLen = 0
        n=0
        while n < (bufLen):
            if ((data[n] < (mean + sd)) and (data[n] > (mean - sd))):
                print "Data [%d] = %d Included" % (n, data[n])
                newSum += data[n] # sum of data which is within +- 1SD of original mean
                newLen += 1 # number of data whic are within +/- 1SD of original mean
            else:
                print "Data [%d] = %d Excluded: Out of range" % (n, data[n])
            n+=1
    CorrMean = newSum / newLen
    print "New n: %d\tNew Sum: %f\tCorrected Mean: %f" %(newLen,newSum,CorrMean)


text:
Johnny-five driving LCD Matrix or call Arduino library from Johnny-five
I would like to know if it's possible to drive an LED Matrix like this one with johnny-five.
If not, how can i call Arduino library/code from johnny-five.
If I Write method on sketch into the Arduino, can I call them from J5 REPL?

After research, it can't be done, as J5 use firmata to drive the Arduino, the only way is to write a library to use with.


text:
Light up multiple LEDs with standard Arduino Uno
I am trying to find out if it is possible to light up multiple LEDs with a standard Arduino Uno. Say I have 500 LEDs and logically I give each one of them a number from 1 to 500. In my test scenario I'd like to say something like "LED No 275 On" and as a result only have this single LED turning on while all others remain off.
Is there a way to do that at all? Or will I have to use many different Arduino Unos for that?

With these kinds of amount, people generally use multiplexing. You could light 500 leds with "only" 45 pins. You can do this yourself, or use a dedicated IC like e.g. the MAX7219.

Probably the simple answer is to use 63 8-bit shift registers, with a LED and resistor attached to each shift register output pin. There are many good examples of using shift registers to add output ports on the internet.
The shift register solution will let you turn on just one LED at a time, or if your power supply can stand it, all 500 at once.
This question shows how to go about the expansion Is there a way to have more than 14 Output pins on arduino?
It also gives some other valid options.

Rectangular matrices and strips of dozens or hundreds of LEDs are available from places like Adafruit and Sparkfun, with added circuitry to allow you to address and manipulate single LEDs easily. Some are single color, some are RGB. Adafruit in particular has many products like this and many tutorials on how to use them.

authors: Коля Мельник


text:
May I use both USB-serial and tx/rx pins at the same time?
I am building a CNC machine based on GRBL code on a uno. I also have found a script to read data on a N64 controller. I know there is not enough pins available to do both codes running on the same arduino, so I was wondering if I could have my GRBL arduino connected to a computer thru USB, and at the same time, have a second arduino reading data from the n64 joystick, create Gcode accordingly, and feed that Gcode to the GRBL arduino through the tx/rx pins of each of them.
I guess I'll have to put a on-off switch on the tx/rx wife to avoid "noise" when I actually send Gcode to the GRBL arduino from the computer.
Does this all make sense?

The usb port and the tx/rx pins are one and the same thing. You can't use one thing for two jobs at the same time. So you will either have to implement some kind of multiplexing system (switches) or come up with a different way of doing things, maybe using the SoftwareSerial library or the Wire Library or investing in a better board with more than one serial port.

Low impedance circuits connected to the TX/RX pins would cause distortion in the serial signal and would interfere with communication.
A switch would help here. Alternately, you could use a Mega 2560 with more IOs, or if you are breadboarding it, use a 1284p chip.
You could also use SoftwareSerial to communicate with the other Arduino on another set of pins.


text:
How can I interrupt a delay() when a button is pressed?
I have created a device that allows my son to track time spent on activities and exchanges that time into a time he can use with his electronics (eTime).
Full code in GITHUB
I am having trouble coding the part of the code that handles the countdown from his earned eTime. As it is right now it can count down and give him a warning when his eTime has run out, but the process can't be interrupted.
I would like to have him be able to stop his eTime and use the remainder later. I tried putting the function in a while loop.
while(digitalRead(button_9)==LOW){
    delay(60000);
    avail_time -= 1;
    if(avail_time<0){
      playAlarm();
      return;
}

This one registers the keypress but ignores the delay.
I have also tried using a for loop to count down and another to check every second for a keypress.
void useTime() {
  for(int i=avail_time+1; i>0; i--){
    displayTime(i);
    for(int minute=60; minute>0; minute--){
      if(digitalRead(button_9)==HIGH){
        avail_time = i;
        return;
      }
      delay(1000);
    }
  }
  while(digitalRead(button_9)==LOW){
    tone(buzzer, 2000);
    }
  noTone(buzzer);
  avail_time=0;
  displayOptions();
  return;
 }

That one does not register the keypress.

look at the blink without delay example sketch

Use timestamp instead of delay(), see Blink Without Delay example

I took a look to your code in Github. I think you also need to debounce for button

You asked "How can I interrupt a delay() when a button is pressed?" The short answer is that you can't. delay() is a blocking function. It can't be interrupted. You need to refactor your code as others have suggested.

You can if you handle your button press in a pin change interrupt handler. But still it is bad practice to use delay(). The only legit use is a timed sequence where you are not doing anything else.

You can use the millis function to check the current 'time'. If you store this, and later call this function again, by subtracting you can see how much time has been passed. so instead of delay(500) you use if (millis() - timeStamp >= 500) { ... to continue your code.
As others said in comments,  you also need to debounce to prevent multiple button triggers.
Edit: Debouncing
There is not a library for debouncing (at least not one on the Arduino site), but you can easily copy the needed code from the following sketch:
Arduino Debounce

I was able to use this solution. I have not implemented debounce yet but I'm looking into it. Is there a debounce library or do I need to implement it myself?

I have updated my answer according to your question in the comment.

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


text:
Errors in code, LM35 temperature logging to web server
trying to experiment with Wemos D1 and LM35. Need to have temperature reading on the ESP IP. Found the following project to be exactly matching my requirements but I am having certain errors in it. Since, I am not that expert with C programming, hence I am unable to resolve the issues and the website admins are also not replying. If you can please help get this program work or point me to some other source. (There are a lot which involve thingspeak.com but I do not want that. A simple WiFi connection to ESP through mobile and get the data on the esp server IP page which is 192.168.4.1 in Wemos.)
Here is the link,
http://blog.circuits4you.com/2016/03/web-server-data-logger.html
First error I get is "temp is not declared". If I declare temp as int then the compiler gives error on spnprintf statement saying "Invalid conversion from int to char*". Tried to read snprintf reference but could not understand the error. Perhaps there will be more errors after this line too. Kindly help.

Read into this. Your code gets an error and it literally describes what's happening: look into it. I'm also voting to close this question because it does not relate to Arduino, it relates to C++ and programming in general.

It's expecting buffer to write all that data: char temp[400];. The snprintf writes at most 399 characters and termination character '\0'. And nobody cares that it generates ugly html:
  char temp[400];
  snprintf ( temp, 400,
""
  ""
    "<meta http-equiv='refresh' content='5'/>"
    "<title>Circuits4You.com Temperature Monitoring Server Demo</title>"
    ""
  ""
  ""
    "
Temperature: %04d
"
  ""
"", analog
  );

It seems like you haven't declared the variable 'temp' from the line
server.send ( 200, "text/html", temp );

It should work fine if you declare it.

I already said that I declared temp as int later on. Then I am getting the second error on snprintf.

You can't declare variables "later on". They have to be declared before they are used.

by later on i meant after executing the program first time...it gave the variable declaration error so I declared it. Later on did not mean later on in the program :D

and is it working now?


text:
Plugged in shield off by one, now all analogues read high
I have a prototyping shield for an Arduino Uno. I accidentally plugged the shield into my arduino so that the pins were all "off by one". I didn't think this was possible, but it turns out that the extra pin just slips between the gaps in the pin headers:

I powered it on not realising. The arduino didn't show any LEDs, so I powered it down, saw my mistake, and plugged it all in again.
Now though A0-A5 are all reading high values (~900-1000 when I do analogRead(A0)), even when I have pulldown resistors on them, and they still read like that when I unplug my shield all together.
The digital writes all work perfectly.
I'm thinking that I've broken the Arduino. Is that possible, or could it be something else?

There is not (yet) enough information to be certain, but it seems likely that you have damaged the Arduino.
If damage has occurred it's more likely to have been caused by what happened on the other side of the board, where pins carry power supply voltages. You do not say what your power source is or where it is connected (USB, 5V in, Vin, ...) but I'd guesstimate that the connection of UNO 5V to Shield 3V3 allowed back feed into the UNO by any of a number of possible paths. UNO Vin connects to shield ground and a second UNO ground connects to a second UNO ground - so if the UNO was powered via Vin you'd expect the power supply to have been shorted. This might damage some power supplies but usually not.
Can you please advise what voltage was connected and to what pin. And do shield pins all offset by 1 on the other side, as I've shown?

Correct, all pins on both sides are offset by one. The power rail on the prototyping shield was connected to the 5V rail from the Arduino. I've also seen really strange behaviour where I have a boolean that keeps toggling between true and false even though nothing is writing to that variable (it did not do this before I plugged in the shield incorrectly), which makes me think that the something is seriously wrong. Pissed off that I broke my expensive ethernet Uno, but that's a learning curve I guess.

@MarkHenderson Look here and note address and seller ID. More below.

Whoah. Their plain Uno's are about 1/3 of the price of locally and their ethernet one is 1/4 of the price of one locally!

One rule in electronics (at least this is one I always practice) is to doble check all connections before plugging power in. I guess if you applied that rule, it would have save you money and time. In your situation particularly, that would have been easy and quick to spot. Should be a lesson learned for you!


text:
Reasons why it is not OK to connect a relay directly from an Arduino digital pin
After looking into various schematics on controlling a relay via an Arduino, I have noticed that, most of the time, transistors are used to switch the separate supply into the relay coil rather than directly supplying the relay with the 5-Volt output from the I/O pin of the Arduino. For example, I have a 5-volt DPDT relay and also a small dc motor. I want to drive both directly from my Arduino UNO (SMD clone) with an Atmel328 processor? Would it be advisable to proceed?
If not (most likely):

Can someone give a detailed explanation and might as well important cautions on current limits and stuff?
How can one control such components without risking the Arduino? What are some common means to accomplish this?
What other devices can generally harm an Arduino board (or any microcontroller unit) in a similar manner?

I'm just a beginner who wants to be extremely cautious. Thanks.

Although recently, with my first encounter with Arduino, I used the I/O pins directly to energize a toy dc motor and change its direction by turning a DPDT relay on and off in the same manner. Nothing seems to be amiss by far.

Processor pins have strictly limited current drive capability.

The rated values may vary depending on whether you want a high or low drive.
Some processors will supply only a few mA and the most you will usually officially get is in the 20 to 30 mA range.
There is usually a total current limit for the processor and only a few pins can provide peak current simultaneously.
Processor pins have significant effective resistance and a high voltage will "drop" as increasing current is drawn and a low voltage will rise as load increases. Pins MAY be specific with a maximum short circuit current but at that point a high pin will be pulled low and a low pin will be pulled high so short circuit current has limited applicability.

Even if you have a say 25 mA per pin rated processor the power available is small. 25 mA · 4V say (1V drop on 5V Vcc) = 100 mW. Most motors will take more than that and only very small motors will run well when powered only by a pin.
Electric motors and inductors will generate significantly high voltages when current is interrupted - voltages of tens of volts can easily result and 100+ volts can happen. Connecting a motor of inductor to a processor pin directly is an invitation to destruction. Murphy will often oblige.

A transistor (bipolar or MOSFET) that will drive typical hobby motors costs 10's of cents (or free from scrapped equipment) and allows the port pin current drive to be buffered and "amplified". Use of a transistor or other buffer is an extremely good idea if you have one or a few processors and do not wish them to die semi-randomly.
MOSFET motor driver - from here - section 8.
Voltages and part numbers are for their example - select to suit.
A NPN biploar could be used with the addition of an input resistor to the transistor base.

Bidirectional driver - if you want the driver to be able to drive a load high and low this circuit will work. from here
The input gate is in this case the internal processor driver. The two MOSFET gates connect directly to the processor pin. Vdd should usually be no higher than processor Vmax_drive_out. Slightly higher can be made to work with suitable design. Much higher voltage loads can be driven with this circuit (or similar) plus one extra transistor.

A buffer such as a ULN2803 (and other family members) will drive 8 channels x 500 mA/channel and several can be paralleled.

A ULN2803 is essentially 8 x "Darlington" transistors with emitters connected to a common ground, 8 x "open collector" (unconnected) collectors, and 8 flyback diodes to deal with over voltage spikes (use optional). (There is a ULN280x family with slightly different input characteristics).
This device provides a reasonably priced means of providing 8 x 500 mA pull down drivers. A load connected from an output to V+ is turned on when the input pin is driven high. Once you've used one a few times you'll find them trivially easy to use and very useful. (There is also a ULN200x family with 7 channels per package).
YouTube "how to" video

Driving a stepper motor

Also here

Driving small DC motors - and quite a lot else.

A zillion examples
Digikey - available in 1's if desired $0.72/1, $0.29 in 1000's.
ULN2803 datasheet

For sale at Sparkfun  - can be had rather cheaper but these are available

The recommended output (source or sink) from an I/O pin is 20 mA. The absolute maximum is 40 mA. Your relay coil is likely to consume more than that, particularly when it initially energizes. This will damage your output pin. Then it will eventually fail.

Nothing seems to be amiss by far.

No, not yet. :)

How can one control such components without risking the Arduino? What are some common means to accomplish this?

Use transistors or MOSFETs.

What other devices can generally harm an Arduino board (or any microcontroller unit) in a similar manner?

Anything that exceeds the maximum voltage or current limits as documented in the datasheet. Coils (eg. in relays and motors) in particular are likely to have a high reverse voltage when they are turned off, which is why you need a snubber diode.

Would it be advisable to proceed?

It would be advisable to take heed of what I wrote above, and to read the many, many articles on the Web about how to drive motors and relays from an Arduino. You are not the first person to attempt this.

To really protect your arduino it's worth putting a photo-coupler on the pin and driving your circuit that way.  Then no stray inductive charge or short can affect the arduino.
They are also called OptoIsolators or Optocouplers.
http://forum.arduino.cc/index.php?topic=143954.0

You're quite right, optoisolators are a great way to go. Another way to do it that's slightly less isolating but still handy is to use an Operational Amplifier (Op Amp) as a buffer. These are also called 'folloer' Op Amps. Note that you can do this with any off-the-shelf OpAmp, you just lay the circuit out a particular way. https://en.wikipedia.org/wiki/Buffer_amplifier#Op-amp_implementation

Have a look at the simple circuit on this PDF from the Arduino Playground.  It shows a single transistor to drive a small relay.
As Russell says in his answer, a ULN2803 or similar is a chip which will allow you to drive several small relays, which is neater than using several transistors, if that's what you want.
(Also note the diode "D1" in the circuit I linked - you need this, it's to protect the transistor from eventually being damaged by inductive spikes generated when the relay turns off.  Some of the ULN-style chips have this diode built in, which is why you don't always see it in schematics.)

Let us look as some basic's, these seem to be the basis of a lot of questions:
A capacitor when power is switched on draws a huge amount of current that tapers off as it gets charged. This curve is also called the RC time constant (this is close but not exact "http://www.electronics-tutorials.ws/rc/rc_1.html" will give a better explanation).
When switching off a capacitor discharges at an exponential rate (RC time constant) depending on the value, charge voltage and the load.  This makes them good for holding power for a short time when the power fails.
An Inductor draws nothing when first switched on but the current increases exponentially until its voltage reaches the supply voltage.
When switched off the inductive field in the inductor collapse causing the polarity to reverse.  The voltage will rise unlimited until typically something externally limits it. The faster it is turned off the quicker the rise time and voltage.  Energy will cease to flow when the inductive charge is dissipated.  Guess where this current goes when the inductive load such as a relay is connected to a port pin?
For this reason you need to put a diode (commonly called a fly wheel diode) across the inductive load.  Google for: "inductor/capacitor charge curve" you will find a lot of nice graphs explaining this. This diode is not necessary if you use an appropriately rated MOSFET (UIS). The UIS (Unclamped Inductive Spike) information is in the MOSFET data sheet.  If you look at the circuit it has the cathode + connected to the most positive side of the power supply.  In this configuration it will not conduct unless the voltage is reversed (when the inductive load is switched off).
Another common misconception is you can load a microprocessor I/O to the maximum. This is bad design. They give you a maximum per pin, per port and for the chip.  At room temperature you will probably get away with it for a while.
Let us assume we have a port with a 40mA load.  The output is 0.005 from the power rail.  Using Ohm’s law we are dissipating 20 milliwatts of power on one pin. At this rate of loading it does not take long to over heat the device because of internal power dissipation.
When the output pin is changing state it draws more current because it has to charge or discharge its internal and the external capacitance, ‘more heat’, more speed ‘more heat’.
If you look some of the specs will give you a maximum temperature, it is for the junction on the die, not the case temperature.  Plastic is a poor conductor so heat sinking the package does not do a lot.  Now consider this along with the ambient temperature.  The ratings are given typically with the device at 25C, guess what happens when it gets warmer.
Have fun,
Gil


text:
OV 7670 + FIFO (AL422B) with arduino
I just brought the camera OV7670 with fifo but I am unable to get the wiring of board with arduino and also I do not find any arduino library for OV7670 with fifo.
It will great if you can help to find some link which can help me.
Thanks,
Somnath

Here is a link to a setup I built to explore the OV7670. There is a spread sheet with the wiring except for power. You are on your own for that, sorry.
https://joseph37920.github.io/OV7670-Explore/

Here is a link. Use google to find more. It is not difficult.

Hi Thanks for quick response . I already visited this page as its only page I found on web which work for camera + fifo https://github.com/arndtjenssen/ov7670.     All other explain camera without fifo ... I tried to check the code and code is basically written for avr and I know arduino is also based son avr only but it doesn't have DDRA and some other couple of register .


text:
Use RFID-RC522 with other Pins
I'm wondering where the pin setting is manifested in the library.
I want to use the RC522 with other digital pins than the default 50-53 pins, because I am using a shield for a display on theese ports.
Where can I change the used ports?
why are two ports user-defineable #define RFID_SS  10 #define RFID_RST 5 while the rest is not?
I am with this Playground-Guide using this library from Github on my Arduino Mega

#define RFID_SS  10

stands for Slave Select on port 10, the SPI is a serial interface, meaning you can connect all kinds of SPI devices to the same wires, as long as slaves have different IO ports.
This is also the reason you don't need to define the other ports because they need to be connected to your SPI.
I suggest you make yourself familiar with this page: http://arduino.cc/en/Reference/SPI
To sum it up. You can change the reset and Slave Select pin out, (those set in the variables) but not the SPI Pins. But you can use the ISCP pins in the middle of the board.

so I can either use ISCP on my board for MOSI MISO SCK. Or I connect the display shield to pins 50-53 and at the same time connect the RFID'sMISO / MOSI / SCK to the same ports 50-53 and the select/reset pins do the rest (choosing where to send data to) for me?

Yes that is correct. Also be aware that some libraries (lib) have the SS pin hard-coded, this is solved by going in to the library and change the value to a variable set through the function.

Sorry I'm a bit late (5 years late) but hopefully this can help someone who's just now trying to do this!
There's an old obscure Sunfounder library, "rfid1.h" that lets you declare every pin. Like this:
rfid.begin(IRQ,SCK,MOSI,MISO,NSS,RST);

It's a bit hard to find the library online these days, but at the bottom of this page (http://wiki.sunfounder.cc/index.php?title=Mifare_RC522_Module_RFID_Reader) if you download the "RFID-RC522_test_experiment" zip file it will have the library in there. The secret is that this library includes a software SPI which is sort of like a software serial for SPI communication. Letting other digital pins be used as MISO etc...
This library also makes it much easier to use multiple RFIDs reliably since they don't have to share all the same pins.
You can find some example code here: https://www.sunfounder.com/learn/RFID_kit_V1_for_Arduino/lesson-29-rfid-entrance-guard-system-rfid-kit-v1-0-for-arduino.html

SPI
The RFID_SS pin is the slave select pin.
So you can have another arduino pin for a LCD_SS select.
Having RfID_SS =low - talk to RFID.
Having LCD_SS =low talk to LCD via MISO.
Note: Drive other slave select High otherwise they'll both get the data.
Having only one device in communication at a time.
Cheers
Nik V


text:
How does one use (specically the wiring) the OV7670 camera with the Arduino Uno?
If one could tell me where each of the pins on the back of the camera go to, that would be great. if someone added the code also that would be awesome.

Due to the extreme RAM limitations, "Arduino Uno" and "Camera" are words that generally do not belong in the same sentence, as only in very select applications can you accomplish something useful, and then rarely in a cost effective fashion.

Im using this type of camera. http://bit.ly/1yZEEAZ

As Chris Stratton already replied, SRAM is an issue. You can add easily 128KB for 3 euro. Normally a camera needs more (in GBs) and this might be tricky, you have to get into SMD and/or costly RAM (since cheap DRAM is a no go for Arduino).
However, you probably also will get into problems with the 16 MHz processor which is probably too slow to handle all the data in time.
Maybe an Arduino Due could be better, but I think you have to go to Raspberry or equal/more.

You need to connect A4 and A5 via pullup register to 3V and to I2C interface on Arduino Uno.
And you need to connect A7 to XCLK signal via 2 registers.
You can find schema and code in my blog: How to connect Arduino Uno and OV7670


text:
Reprogram Arduino Mega 2560 using Duemilanove?
Experiencing that Mega 2560 uploading problem. Tried updating the IDE, worked for a while but symptoms went back. Now i want to reprogram that chip.
I'm asking this question cuz hardware ain't free and shipping is not instant.
I don't have a programmer. So we already know that we can program an arduino board with another arduino board as a programmer. However i just have a Duemilanove available. Will this work? Please do not answer if you're not sure.


text:
PWM pins weird on Arduino Mega, works on Arduino Uno
I've bought one of those cheap 2.4" TFT LCD resistive touchscreens, one of these:
It works great on my Arduino Uno, using the code from this github repository.  Now I'm trying to get this to work on my Arduino Mega.
On the Arduino Uno, the LCD controller data lines are configured as:
data[0:7] = PORTB[0:1] | PORTD[2:7]

ie. data pins 8, 9, 2, 3, 4, 5, 6, 7 make up the LCD controller data lines.
On the Mega, the pin numbers are the same but the ports are configured differently, so that:
data[0:7] = ((PORTH >> 5) & 0x03)
   | ((PORTH << 3) & 0xc0)
   | ((PORTG >> 1) & 0x10)
   | ((PORTE >> 2) & 0x0C)
   | ((PORTE << 2) & 0x20)

I've rewritten the TFTLCD::read8 and TFTLCD::write8 functions accordingly.
The screen doesn't work, though.  I've cut example code down to just resetting the LCD controller and reading the chip ID register, ie:
Tft.writeData(0);
Tft.writeData(0);
Tft.writeData(0);
Tft.writeData(0);

Tft.writeCommand(0);
unsigned id = Tft.readData();

Now, 9 times out of ten, this obtains the correct device ID, 0x9325.  But the other time, it obtains the device ID of 0.
I initially suspected that this was due to the Mega running somewhat faster, but liberally sprinkling delayMicroseconds(10) through the writeData, writeCommand and readData functions doesn't seem to make any difference.
Is there something that I'm missing that is messing with the use of the PWM lines on the Arduino Mega as ordinary digital port pins?

Never mind; this was me making a mess of the bit masking.
See this github repository for working code with Arduino Mega.


text:
'Keyboard' not found when trying to use Keyboard.write from the <Keyboard> library
I am trying to get a response from the arduino when I press a key, but when I try to upload the code it says that it could not find 'Keyboard' with 'Keyboard.write'. Here is my code. Ignore the bits with servo stuff, that is for the project later on. I am using the arduino mega 2560.
  #include <Servo.h>
  #include <Keyboard.h>

Servo myservo;
Servo myservo2;

int pos = 0;
int pos2 = 0;
String comdata = "";
int lastLength = 0;

void setup() {
myservo.attach(12);
myservo2.attach(11);
Serial.begin(9600);
pinMode(2, INPUT_PULLUP);
Keyboard.begin();
}

void loop() {
if (Serial.available() > 0) {
 // read incoming serial data:
 char inChar = Serial.read();
 Keyboard.write(inChar + 1);
}

}

The Mega2560 can't be a keyboard. It lacks the required hardware.
Instead you need to use one of the pure USB boards, like the Leonardo.

To use USB communication (such as mouse or keyboard) you must have a arduino that uses an ATMEGA32U4. These are so far, the only boards that can work as a USB device.


text:
Not sure if my Arduino Uno is damaged
When I plug the USB cable to my Arduino and try to upload a sketch I get thtis error:
avrdude: ser_open(): can't open device "/dev/cu.usbmodem1411": No such file or directory
ioctl("TIOCMGET"): Inappropriate ioctl for device

when I go to Tools > ports I can't find the USB port.
The Arduino still working and green ligh is on, so what is the problem exactly?

Does the Uno show up under  -> "About this Mac" -> "More info" -> "System Report"->"Hardware"->"USB"?

You should really search on Arduino Inappropriate ioctl possibly with mac that would give you some results worth reading.
http://arduino.stackexchange.com/questions/13299/inappropriate-ioctl-for-device or https://forum.arduino.cc/index.php?topic=292284.0 and  http://askubuntu.com/questions/646254/arduino-serial-port-com1-problem are all people with the same error message. Try what worked for them.

Probably never mind, since the Arduino isn't even recognized by the PC, try to fix that first. If you try another Arduino, you would be able to tell if the problem is on the PC or on the Arduino.

Actually, you might still want to check out those links. Try running your IDE as administrator (or what it is at mac).

Have heard of similar problems with Mac. Not a Mac user myself. Sometimes the Arduino can somehow trigger a current fault in the USB of Mac's and will need to be shut down and rebooted for it to work again.
Try rebooting your Mac.
If you have a cheap chinese Arduino you might need other drivers for it. Check what chip you have closest to the usb connector.

I have tried with 2 Mac laptops, same thing happened. an electronics guy told me that the IC is burnt, is this right?

I would check that you have the correct driver before i would make that assumtion.

@AfnanHumdan and I would check it again, because the "the IC is burnt" is the common way to say "I don't have the time to look at it, so just change it". Moreover you didn't say if the board ever worked. Then try using another pc (not a mac) just to double check. If it doesn't work, maybe flashing again the firmware on the atmega16u2 (the usb-serial interface IC) can solve the problem..

The Arduino only requests 100mA from the USB port. If you draw more than that it may decide to cut you off. 100mA is somewhat conservative (they could have set it to ask for 500mA) but it does allow it to work on an unpowered hub without the hub shutting it off - as long as you stay within that 100mA budget. Many systems ignore that limit though and provide many amps of power, but the Mac may be more sensitive.

@Majenko the Arduino request 100mah and could ask for 500 mah. I beg you to explain this. The usb 2.0 standard says a port should be able to deliver 500mah, whether the arduino draws that from the port or not is irrelevant unless exceeding 500mah where the controller might disconnect your device.

You are thinking purely electrical. USB also contains a protocol. That protocol as a portion in it whereby the device tells the host "I will require this much power". If that request exceeds what the port can provide it should be disconnected (unpowered hubs can only provide 100mA per port). If the device draws more than it has told the host it will be using then the host is at liberty to disconnect the device to protect itself.

I just read up on this, and you are correct according to the  standard. I however are using hubs, always and have no problems drawing up to close 3 A before being cut off from those, with only power pins connected.

I was also facing this type of issue. But it has resolved itself now. I go to Tool >> Select Port after Select USB modem its work fine.

This does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. You can also add a bounty to draw more attention to this question once you have enough reputation. - From Review

I can't agree this isn't an answer. It clearly spells out what to do to resolve the issue. If that doesn't solve the problem that is another issue. To whoever has been flagging this, answers are not to be flagged merely because they are wrong.

@NickGammon, the question is a Mac specific problem, where no ports are listed in IDE. how does this 'late' and 'me-to' answer answer the question? ('my' previous comment was generated by SE)

@Juraj On the Mac you get Tools -> Ports, as mentioned in the question. Bad answers don't have to be flagged for moderator attention. Just leave a comment stating why it won't work in your opinion and optionally vote it down.

@NickGammon, SE system asked me if this is a low quality late answer that should be deleted. I didn't flag it directly

Yes, but you agreed, right? You can skip answers that don't seem low quality. It's just an algorithm.

@NickGammon, yes I agreed.  the SE system added the answer to review because it is late and short and I reviewed it and I think, the answer doesn't answer the question. because if the list is empty you can select nothing. but you are the admin and you can delete the flag and let it be. there was an other late answer in the review list and it was ok. and then some answers I skipped because I was not sure


text:
How to use unregulated VIN voltage?
I have recently bought an Arduino Mega, and I am powering it with a USB charging port, 5V at 1A. I need to use the 1A with a transistor, since the Arduino itself can only supply a maximum of 20mA through one pin.
So I was wondering, is there any way to access this unregulated power source? Would the VIN pin serve this purpose, or is there no way to access the 1A current without pulling apart the USB cable?

The VIN port is connected to the barrel jack. It must only be used if you are powering the board through that jack.
To access the USB power just use the 5V pin - it is directly connected to the USB.
However, the USB, although the socket it is plugged into can supply more, is limited to 500mA. This is because of a 500mA auto-resetting polyfuse on the USB power input (the large gold and dark green rectangle next to the USB socket - mine has either XE05 or 503X on it depending on which way up you hold it).

Okay, thank you for clarifying. I guess I'll need to power it another way, so I can access the power source... or sacrifice a USB cable!

The VIN port is connected to the barrel jack. - via a diode. Thus Vin will be around 0.7V less than what you supply at the barrel jack.


text:
Max current through an Arduino Mega?
How much current can I put through the pins of an Arduino Mega at the same time?
The situation: I am building a 7x7x7 LED cube, and my plan was to multiplex in 7 layers of 49 pins, lighting each layer, one at a time. This would mean each pin on the Arduino Mega would only have to supply max. 1 LED at a time.
However, if all 49 LEDs in one layer were on, it would presumably draw 49*20mA (from the LED specs sheet), which is 980mA. This seems like quite a lot of current to put through an ATMega chip, so I was wondering if I could do it, either continuing like this, or using transistors to control the lighting of each layer, or what?
Any help or advice is appreciated!
EDIT: Using ATMega2560, not ATMega328 or alternate.

What does the ATMega datasheet say?  The maximum output current on microcontrollers I've used is around 20 mA, so your 980 mA is totally out of range - you'll need transistors to handl that much current.

@PeterBennett Yeah, the datasheet says the 20mA is per pin, and for an Arduino Uno. For an Arduino Mega, per pin is 40mA. The 980mA figure quoted is in total, over 49 pins.

The ATmega 2560 (assuming that's the chip on your Arduino Mega) has an absolute limit of 40mA on each pin, and 200mA in total for all pins. So yes, you will not be able to drive that load directly from the Arduino.

With external circuitry however, anything is possible. If it were me, I'd use some TPIC6B595 IC's to drain current and BC635 NPN's to source it.
The 595's can sink up to 150mA each (so up to 8 LEDs at 18.75mA each, use a 270Ω resistor in series with each LED if you're running everything from 5V.) You would need 7 595's for 49 LEDs (49 / 8 rounded up.)
You can daisy chain the serial in/outs on them so you just need to shift out 8 bytes from the Arduino (either using SPI or the software equivalent, shiftOut or whatever it's called, on any digital pin.)
TPIC6B595N Datasheet
To source current, BC635's are rated up to 1A with a typical current gain (hFE) of 100. Collector pin goes to 5V, Emitter pin goes to all the LED anodes on a layer, Base pin connects in series to a 510Ω or 470Ω resistor and an Arduino digital pin. You would need 7 635's, one for each layer. They turn 10mA from a digital pin into 1A from the power supply.
BC635 Datasheet
Speaking of power supplies, you will not be able to power the whole thing from the Arduino 5V pin (especially if powered from USB.) You will need an additional 5V power supply. If you want simplicity you could use a L7805 voltage regulator and stick a heatsink on it.
L7805 Datasheet
All of these are popular components which can be obtained from eBay for next to nothing.
If you have more questions specific to Arduino, they might be better suited to the Arduino Stack Exchange.
Arduino Stack Exchange Link

I should mention that by multiplexing each LED will only receive 1/7th of the current over time. That is to say, if you were putting 18.75mA through each LED they would only get the equivalent of 18.75mA / 7 (2.68mA.)

So what if I went over the max recommended current for the LEDs? I asked for 180 ohm resistors and I got given 150 ohm instead at Maplin's, and didn't check before I was out. The blue LEDs have a voltage drop of 3.3V which gives 3.3/0.150 = 22mA, which is over the recommended 20. But since I am multiplexing, this means I'd have an equivalent of 22/7 ≈  3.1mA?

Ummm I think that should be (5V - 3.3V) / 150Ω = 11mA so you're fine in either case.

You're on the right track here. In the datasheet for the ATmega1280 I find this box:

What you want to look at is DC Current Vcc and GND Pins  ....  200.0 mA
This is the total limit of all the current going through the chip (because everything must come through Vcc), and it is the absolute maximum. Don't go near it. You need to boost this with some transistors.

It's listed in the Electrical Characteristics of the specific MCU used in the Arduino you have.
For the Mega2560, its remarkably similar to the 328 in the Uno.
Absolute Max, 40mA per pin, 200mA VCC or GND current. 20mA per pin recommended max. A huge note, various ports have individual limits:

3: Although each I/O port can sink more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady state
  conditions (non-transient), the following must be observed:
  ATmega1281/2561:
  1.)The sum of all IOL, for ports A0-A7, G2, C4-C7 should not exceed 100mA.
  2.)The sum of all IOL, for ports C0-C3, G0-G1, D0-D7 should not exceed 100mA.
  3.)The sum of all IOL, for ports G3-G5, B0-B7, E0-E7 should not exceed 100mA.
  4.)The sum of all IOL, for ports F0-F7 should not exceed 100mA.
  ATmega640/1280/2560:
  1.)The sum of all IOL, for ports J0-J7, A0-A7, G2 should not exceed 200mA.
  2.)The sum of all IOL, for ports C0-C7, G0-G1, D0-D7, L0-L7 should not exceed 200mA.
  3.)The sum of all IOL, for ports G3-G4, B0-B7, H0-B7 should not exceed 200mA.
  4.)The sum of all IOL, for ports E0-E7, G5 should not exceed 100mA.
  5.)The sum of all IOL, for ports F0-F7, K0-K7 should not exceed 100mA.
If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater than the listed test condition.
4: Although each I/O port can source more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady state conditions (non-transient), the following must be observed:
  ATmega1281/2561:
  1)The sum of all IOH, for ports A0-A7, G2, C4-C7 should not exceed 100mA.
  2)The sum of all IOH, for ports C0-C3, G0-G1, D0-D7 should not exceed 100mA.
  3)The sum of all IOH, for ports G3-G5, B0-B7, E0-E7 should not exceed 100mA.
  4)The sum of all IOH, for ports F0-F7 should not exceed 100mA.   ATmega640/1280/2560:
  1)The sum of all IOH, for ports J0-J7, G2, A0-A7 should not exceed 200mA.
  2)The sum of all IOH, for ports C0-C7, G0-G1, D0-D7, L0-L7 should not exceed 200mA.
  3)The sum of all IOH, for ports G3-G4, B0-B7, H0-H7 should not exceed 200mA.
  4)The sum of all IOH, for ports E0-E7, G5 should not exceed 100mA.
  5)The sum of all IOH, for ports F0-F7, K0-K7 should not exceed 100mA.