Moving cursor on LCD and changing highlighted value

Firstly, you should set the time variables outside the main loop (as a global variable). If you put them in the main loop, the time would always reset to 11:11:11 after 0.6s of delay.

  lcd.setCursor == lcd.setCursor(0,3)

I dont think you can do this (unless the function returns you with the location of the cursor, have to check the header file of the library).

Instead, you should keep track of the location of the cursor with another variable (as mentioned by gre_gor), say int curLoc. But note that you have to keep track of the range of values it can go. (0 < curLoc < 16)

To summarise, the code could look like this:

#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

int hours = 11;
int minutes = 11;
int seconds = 11;

int curLoc = 0; //Current cursor location (x-axis)

void setup() {
  lcd.begin(16, 2); //format of display
}

void loop() {
  lcd.setCursor(0,0);
  lcd.print(hours);
  lcd.print(":");
  lcd.print(minutes);
  lcd.print(":");
  lcd.print(seconds);
  lcd.noBlink();
  delay(300);
  lcd.blink();
  delay(300);

  //move cursor right;
  if (buttons & BUTTON_RIGHT) {
    //Keep the tracker in range
    if(curLoc >= 0 && curLoc < 16){
    curLoc += 1;
    }

    if(curLoc == 3)
    {
      minutes += 1
     }

}


Yes, that will work. However, ignore the entire description.

That is NOT a buck regulator - it is a low-dropout linear regulator.  Thus it will waste power as heat - the more current you draw the hotter it will get.

The '1117' range of regulators are pretty much ubiquitous. I use them in a wide range of products and situations where power consumption isn't critical (i.e., not battery based products).

For lower power requirements you want to get a real buck regulator. Something more like this: http://www.ebay.co.uk/itm/301842020065

Note that it's an adjustable module, and you will need to first use a multimeter to adjust the output to 3.3V before you connect it up.

Because they are adjustable they are a great thing to keep around since you can use them for all sorts of different situations.


When i press a button to subtract 1 from 5 it skips to 3

Your main problem is that you aren't looking for a change in buttons. You're only doing your adding or subtracting while a button is pressed.

That means, all the time you're holding btnLEFT in your total is incrementing until it hits your limit.

You need to remember the button state from the previous iteration of loop() and compare it to the current state - and only if they differ do you need to do anything.

Also you should perform your constrain immediately after your addition or subtraction. As it is, you add or subtract, display the new value (I assume you do - I don't see the code for that), and only afterwards do you then chop the value back down to +/-4 (assuming it's outside the range). So your 5 becomes 4, and your next subtraction takes you to 3.


How do I redefine the overlfow of compare interrupts in Arduino programming?

What about using a switch statement inside the ISR function and reroute the flow depending on the value of the global variable used in the switch?

uint8_t status = 0;

void myInterruptFn() {
  switch(status) {
    case 0:
      // do something
      status = 1;
      break;
    case 1:
       // do something else
       status = 0;
       break;
   }
}


Check '{' and '}' pairs in your code.

void loop(){
    long duration, distance;
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = (duration/2) / 29.1;
    if (distance <= 4) {
        inTime= rtc.getTimeStr();
        Serial.println(inTime);

   }
} //<--- what is this little fella doing here?
    else if (distance >= 5 || distance <= 0){
    Serial.println("Out of range");
    }

delay(500);
}


Try Pin digital pins 0 (RX) and 1 (TX), as they also should be Serial0 on ArduinoMega (PWM 0 and 1)

see:
https://www.arduino.cc/en/Reference/Serial

The Arduino Mega has three additional serial ports: Serial1 on pins 19 (RX) and 18 (TX), Serial2 on pins 17 (RX) and 16 (TX), Serial3 on pins 15 (RX) and 14 (TX). To use these pins to communicate with your personal computer, you will need an additional USB-to-serial adaptor, as they are not connected to the Mega's USB-to-serial adaptor. To use them to communicate with an external TTL serial device, connect the TX pin to your device's RX pin, the RX to your device's TX pin, and the ground of your Mega to your device's ground.


It's pretty easy to follow if you indent and break it up right.  Let me add some annotation too:

Usage Page Gen Desktop Ctrls(01)  // Usages describe what the
Usage Game Pad                    // following data is used for.
Collection Application
    Usage Pointer        // Use the settings for a physical
    Collection Physical  // pointing device
        Usage X       // It has four axes -
        Usage Y       // X, Y, Z and some other undefined axis.
        Usage Z
        Usage Undef
        Logical Min(80) // Output the values 0x80 to 0x7F, which when
        Logical Max(7F) // interpeted as signed bytes is -128 to 127.
        Physical Max(FF00) // The input has a range 0 to 255
        Unit(0000)
        Unit(0000)
        Report Size(08)  // The report value is 8 bits long,
        Report Count(04) // and there are 4 of them (one per axis)
        Input(00000010)  // This ends this "input" section.
    End Collection

    Usage Hat Switch // Describing a HAT Switch now.
    Logical Min(01)  // Interpret it as a value between 1 and 8
    Logical Max(08)
    Physical Min(00) // The input to it is between 0 and 0x3B01.
    Physical Max(3B01) // Not sure that value is interpreted properly.
    Unit(14)
    Report Size(04)  // The report has 4 bits in it,
    Report Count(01) // and there is just one of them.
    Input(00000010)  // And end the input section.

    Usage Page Button(09)  // Next come the buttons.
    Usage Min(01)      // These are basically button numbers
    Usage Max(04)      // - there's 4 buttons, 1 through 4.
    Logical Min(00)    // A button is either off (0)
    Logical Max(01)    // or on (1).
    Report Size(01)    // And can only have one state, so size 1.
    Report Count(04)   // There's 4 buttons, so 4 reports.
    Input(00000010)    // And end the input.

    Report Count(08)   // This is a special one. It keeps the settings
    Input(00000001)    // from before (the haven't been changed), but
                       // is just a dummy one to pad out the data to
                       // the right size. Alignment is key.

    Usage Page LEDs(08)    // Now we have 4 LEDs with an
    Usage Slow Blk On Time // 8-bit PWM value. 0-FF which doesn't
    Logical Min(00)        // need interpreting, so 0=0 and FF=FF.
    Logical Max(FF00)
    Physical Min(00)
    Physical Max(FF00)
    Report Size(08)    // As I said, 8 bit,
    Report Count(04)   // and there's 4 of them.
    Output(10000010)   // And it's output.

    Unit Exp(00)   // Now there seems to be a bit of junk.
    Unit(00)
    Unit Exp(00)
    Unit(00)
    Unit Exp(00)
End Collection Game Pad // And the end.

So interpreting that, you get a report sent to you that has:

Byte     Function
0        X Axis 0-255 which you map to -128 to 127
1        Y Axis 0-255 which you map to -128 to 127
2        Z Axis 0-255 which you map to -128 to 127
3        Another Axis 0-255 which you map to -128 to 127
4        Upper 4 bits buttons, lower 4 bits HAT direction
5        Padding byte to make ita multiple of 16 bits long

And you can send a 4 byte report where:

Byte     Function
0        LED 1 PWM
1        LED 2 PWM
2        LED 3 PWM
4        LED 4 PWM

Those "LEDs" could be force feedback motors or vibrators.

Also I suspect there is maybe a small amount of corruption or mis-interpretation of multi-byte values in the output.


Ok then.

I just tried that again and it simply seems that the wiring shown on the tutorial is not good at all.
I made another wiring that worked exactly fine.


How to write a more compact ANDed conditions with if statement?

There is a standard C function for this, memcmp(). It performs a memory block compare and can be used like this:

if (!memcmp(bt, rfid.serNum, sizeof(bt))) {
  lcd.clear();
  lcd.print("card accepted");
  digitalWrite(green_led,HIGH);
  digitalWrite(red_led,LOW);
}
else {
  ...
}

Ref. http://www.cplusplus.com/reference/cstring/memcmp/


MatLab connection to Arduino using Bluetooth

As discussed in the comments, the "problem" seemed to be Matlab adding a "New Line" which is a decimal 10 in ASCII.

  asciitable.com Decimal 10 is the ASCII code for a "New Line" so it appears your Matlab send code will add a "New-line" after each sent value. – Paul Apr 14 at 8:15

    thank you very match the problem is solved – abbas hussien 5 hours ago

You might want to accept this answer so that this question gets "closed" and the site's statistics will be more accurate.
It will also avoid this question being bumped up by the system and people reading into something that has already been solved.


Fio Keyboard program out of control, how to reset?

Hehe... This is a fun one to try and get out of. The normal way is to reflash the bootloader...

If it's the same as the Leonardo you get about 8 seconds after a reset while just the bootloader runs before it starts to spam everything with text. So you can try:

Open notepad or something similar
Plug in the board
Press and hold the RESET button (or connect the RESET pin to GND with wire)
Open the IDE and load Blink.ino

Now the tricky bit.  If the correct serial port isn't selected, you need to, within the space of 8 seconds:

Release the reset button.
Let the PC enumerate the device
Open the serial ports menu and select the right port
Press and hold the RESET button again.

Now you can program it, in a similar way:

Press UPLOAD in the IDE.
Just before it finishes compiling (turn on verbose output can help you time it better) release the RESET button.

If you timed it right the bootloader should run and accept the new program before the existing sketch runs and starts spamming everything.


error while loading libtinfo.so.5 - SOLVED

Install libtinfo5, the terminfo library.

If that doesn't help, you can try to debug the problem yourself. First,
check which libtinfo avrdude is looking for:

ldd arduino-1.7.8-linux64/hardware/tools/avr/bin/avrdude_bin | grep libtinfo

On my Ubuntu, I get this:

libtinfo.so.5 => /lib/x86_64-linux-gnu/libtinfo.so.5 (0x00007fa74a888000)

Next, see where your libtinfo is installed:

find /lib /usr/lib -name 'libtinfo*'

On my system I get:

/lib/x86_64-linux-gnu/libtinfo.so.5
/lib/x86_64-linux-gnu/libtinfo.so.5.9

Do you have any discrepancy between the two?


100 Hz is pretty trivial. See my page about timers.

This sketch can detect frequencies up to about 5 MHz:

// Timer and Counter example
// Author: Nick Gammon
// Date: 17th January 2012

// Input: Pin D5

// these are checked for in the main program
volatile unsigned long timerCounts;
volatile boolean counterReady;

// internal to counting routine
unsigned long overflowCount;
unsigned int timerTicks;
unsigned int timerPeriod;

void startCounting (unsigned int ms)
  {
  counterReady = false;         // time not up yet
  timerPeriod = ms;             // how many 1 ms counts to do
  timerTicks = 0;               // reset interrupt counter
  overflowCount = 0;            // no overflows yet

  // reset Timer 1 and Timer 2
  TCCR1A = 0;
  TCCR1B = 0;
  TCCR2A = 0;
  TCCR2B = 0;

  // Timer 1 - counts events on pin D5
  TIMSK1 = bit (TOIE1);   // interrupt on Timer 1 overflow

  // Timer 2 - gives us our 1 ms counting interval
  // 16 MHz clock (62.5 ns per tick) - prescaled by 128
  //  counter increments every 8 µs.
  // So we count 125 of them, giving exactly 1000 µs (1 ms)
  TCCR2A = bit (WGM21) ;   // CTC mode
  OCR2A  = 124;            // count up to 125  (zero relative!!!!)

  // Timer 2 - interrupt on match (ie. every 1 ms)
  TIMSK2 = bit (OCIE2A);   // enable Timer2 Interrupt

  TCNT1 = 0;      // Both counters to zero
  TCNT2 = 0;

  // Reset prescalers
  GTCCR = bit (PSRASY);        // reset prescaler now
  // start Timer 2
  TCCR2B =  bit (CS20) | bit (CS22) ;  // prescaler of 128
  // start Timer 1
  // External clock source on T1 pin (D5). Clock on rising edge.
  TCCR1B =  bit (CS10) | bit (CS11) | bit (CS12);
  }  // end of startCounting

ISR (TIMER1_OVF_vect)
  {
  ++overflowCount;               // count number of Counter1 overflows
  }  // end of TIMER1_OVF_vect

//******************************************************************
//  Timer2 Interrupt Service is invoked by hardware Timer 2 every 1 ms = 1000 Hz
//  16Mhz / 128 / 125 = 1000 Hz

ISR (TIMER2_COMPA_vect)
  {
  // grab counter value before it changes any more
  unsigned int timer1CounterValue;
  timer1CounterValue = TCNT1;  // see datasheet, page 117 (accessing 16-bit registers)
  unsigned long overflowCopy = overflowCount;

  // see if we have reached timing period
  if (++timerTicks < timerPeriod)
    return;  // not yet

  // if just missed an overflow
  if ((TIFR1 & bit (TOV1)) && timer1CounterValue < 256)
    overflowCopy++;

  // end of gate time, measurement ready

  TCCR1A = 0;    // stop timer 1
  TCCR1B = 0;

  TCCR2A = 0;    // stop timer 2
  TCCR2B = 0;

  TIMSK1 = 0;    // disable Timer1 Interrupt
  TIMSK2 = 0;    // disable Timer2 Interrupt

  // calculate total count
  timerCounts = (overflowCopy << 16) + timer1CounterValue;  // each overflow is 65536 more
  counterReady = true;              // set global flag for end count period
  }  // end of TIMER2_COMPA_vect

void setup ()
  {
  Serial.begin(115200);
  Serial.println("Frequency Counter");
  } // end of setup

void loop ()
  {
  // stop Timer 0 interrupts from throwing the count out
  byte oldTCCR0A = TCCR0A;
  byte oldTCCR0B = TCCR0B;
  TCCR0A = 0;    // stop timer 0
  TCCR0B = 0;

  startCounting (500);  // how many ms to count for

  while (!counterReady)
     { }  // loop until count over

  // adjust counts by counting interval to give frequency in Hz
  float frq = (timerCounts *  1000.0) / timerPeriod;

  Serial.print ("Frequency: ");
  Serial.print ((unsigned long) frq);
  Serial.println (" Hz.");

  // restart timer 0
  TCCR0A = oldTCCR0A;
  TCCR0B = oldTCCR0B;

  // let serial stuff finish
  delay(200);
  }   // end of loop

  Or is there a conventional frequency that digital devices usually use for output?

No.

  Wouldn't it be the case that if Arduino expects 100Hz signal, but the signal is 200Hz it would miss half the inputs? For: (1 0 1 0 0 1...)

No.

Why would it "expect" a frequency? It isn't a person expecting a chocolate cake on its birthday.

  So whatever frequency the sensor sends its data in - be it 100Hz or 5Mhz - Arduino is smart enough to read all the voltage signals faithfully?

I'm not quite sure what you mean by "read all the voltage signals" which seems to imply you want to measure the voltage.

  so every 1/100 of a second it varies the voltage (or keeps the old voltage if the next signal is the same as the previous one)

But then you say:

  let's assume that the 1 voltage is high enough (but not too high) for Arduino to register a 1, and the 0 voltage is also within the threshold for Arduino to register a zero (say 5V for HIGH and 0.5V for LOW). It's the frequency of the signal I'm concerned with.

The voltage levels for 0 and 1 are documented in the datasheet. For the Atmega328P for most pins they are as follows:

You can see that if Vcc is 2.4V or above then LOW is -0.5V to 0.3 * Vcc, which if Vcc is 5V then a LOW is -0.5 to 1.5V.

Similarly a HIGH is 0.6V * Vcc to Vcc + 0.5, so if Vcc is 5V then a HIGH is 3V to 5.5V.

In between 1.5V and 3V then the digital status would be undefined.

So, if your LOW and HIGH are in those voltage ranges, yes you can detect the frequency of the signal.

I'm not sure about the bit where you said "keeps the old voltage if the next signal is the same as the previous one". That seems to imply that if the signals stay the same (eg. for a second) then the voltage won't change at all, and thus the frequency will be zero.


Why does opening the Tools menu take so long?

It's an RXTX issue. RXTX is the native serial library used to make the IDE talk to the boards.

On some Windows installation, with some Bluetooth things (both dongles or integrated), when enumerating serial devices, these dongles scan the air for remote serial devices. Hence, the IDE stays stuck, waiting for RXTX serial device enumeration to end. This issue has been acknowledged a lot of times, see for example #1375, #532, #200 and #143

As far as I understand, this issue does not affect linux or mac because of the different way the scan occurs. On linux it's a plain filtered file listing of /dev. Similarly it's on mac. On windows, it uses native API calls.

Some fixes are available in the 1.5 series but I suggest switching to the latest 1.5.6 release as RXTX was replaced by JSSC, a more modern and simpler library.


Can arduino interrupts occur in a middle of if statement?

Yes, an interrupt can occur at any time and can change the values during a calculation. And since you work with unsigned long variables (which are 4 bytes as I remember), it is also possible, that the calculation uses the old value for the first bytes and the new value for the other bytes, meaning that the used value for calcuation is totally garbage.

To prevent that your checks must either be atomic (meaning consisting only of 1 base instruction, which cannot be interrupted, e.g. handling only 1 byte) (that is not possible here), or you must prevent the calculation from being interrupted. For this you can turn off all or only the corresponding interrupt. To turn off all interrupts you can use noInterrupts() and interrupts() to turn them on again.

But it is questionable, why you need to update this time directly in the ISR. Instead you could only set an atomic flag (1 byte) and check this flag in the loop. If the flag was set, reset it and save the millis value. If you loop runs fast enough (which seems the case, since you already use it to set a millis timestamp) that should be sufficient

Both ways can be used and it depends on you, if it's ok to turn of interrupts for a short time, since you might miss an I2C interrupt this way.


You cannot do that with ordinary servos. This is because of the way the
communication protocol is built: the only thing a servo understands is a
command which in effect means “go to that position as fast as you can”.
You can achieve smooth movements by updating the requested position (the
so called “set point”) many times by tiny steps, but you still have the
problem at startup.

I see two possible solutions to your problem:

Make sure you know the position at which the servo was left when you
powered down your Arduino. You can either arrange to leave it always
at the same position, or you can store the last position in EEPROM
before powering down. Then, at startup, you initialize the servo with
that last known set point.
Use a special type of servo known as a feedback
servo,
or convert a regular
servo to
get a feedback. A feedback servo is a type of servo that tells you
its actual position, so you can arrange for the initial set point to
match that position.


Which board's bootloader is on the microcontroller?

It depends on which bootloader you loaded, when you write your bootloader with AVRDude you specify the hex file, Which Hex file did you specify?


How do I make Arduino IDE use a specific version of GCC in Debian?

As Majenko pointed out, I should have used a tarball from the official site instead of the repositories. Which makes me wonder why that package wasn't deprecated or something...


Here are a few items to consider.

From #define pw 3 you are working with PD3, INT1.  As one of the Atmega328 Uno's two external interrupts, INT1 supports RISING and FALLING events separately.  Pin change interrupts (PCIs) on pins other than 2 or 3 of the Uno won't separate them and in the interrupt routine (one interrupt routine in that case, not two) you will need to test which occurs by reading the pin.
Serial communication depends on interrupts and won't work in an interrupt handler.  Instead, set a flag (via a volatile byte variable) to test in your loop().
For testing, put pwm_on(pwm) in setup() instead of loop().
In loop(), compute seconds = milli()/1000 and if seconds != prevsec, set prevsec=seconds, enable your PCI or external interrupt, then enter a loop that waits for a flag and takes a reading.  Or, in the interrupt handler, both set a flag and take a reading into a volatile variable.
If you only need to measure the quantities a few times per second, or a few times per minute, you could just busy-wait for the condition, then trigger a sample-and-hold, then convert analog to digital via analogRead().

Regarding sample-and-hold: Unless you change the ADC sampling rate, analogRead() will take up to 100 microseconds per reading.  If your input waveform is 62.5 KHz, it will toggle about about six times while being measured, which if measured directly is likely to give a random result.  However, if you use a sample-and-hold circuit, you can hold the ADC input constant until your measurement completes.

An alternative to using a sample-and-hold is changing the ADC sampling speed. See post #5 in thread Faster Analog Read? on forum.arduino.cc.  If you get the sample time down to 8 to 12 microseconds you can do ok with a busy-wait method.  Ie, when your code wants a reading, it has a loop that measures the PWM line over and over, and starts an ADC conversion shortly after the PWM gets to the state desired for the measurement.


Setting up the MMA8452 to trigger interrupt

I played around more with it, and this code works:

void MMA8452::initMMA8452(unsigned char fsr, unsigned char dr, unsigned char sr, unsigned char sc, unsigned char mt, unsigned char mdc)
{
    MMA8452Standby();

//Set up the full scale range to 2, 4, or 8g.
if ((fsr==2)||(fsr==4)||(fsr==8))
    writeRegister(XYZ_DATA_CFG, fsr >> 2);
else
    writeRegister(XYZ_DATA_CFG, 0);

writeRegister(CTRL_REG1, readRegister(CTRL_REG1) & ~(0xF8));
if (dr<= 7)
    writeRegister(CTRL_REG1, readRegister(CTRL_REG1) | (dr << DR0));
if (sr<=3)
    writeRegister(CTRL_REG1, readRegister(CTRL_REG1) | (sr << ASLP_RATE0));

writeRegister(CTRL_REG2, readRegister(CTRL_REG2) | (LP << SMODS) | (LP << MODS) | (1 << SLPE));  //LOW POWER MODE IN SLEEP & ACTIVE STATES WITH LOWEST SAMPLING
writeRegister(ASLP_COUNT, sc);

// Set up interrupt 1 and 2: 1 = wake ups, 2 = data
writeRegister(CTRL_REG3, (1 << WAKE_FF_MT) | (1 << IPOL));  // Active high, push-pull interrupts, sleep wake up from motion detection
writeRegister(CTRL_REG4, (1 << INT_EN_ASLP) | (1 << INT_EN_FF_MT) |  (1 << INT_EN_DRDY));  // DRDY ENABLE SLP/AWAKE INTERRUPT (INTERRUPT THROWN WHENEVER IT CHANGES) & MOTION INTERRUPT TO KEEP AWAKE
writeRegister(CTRL_REG5, (1 << INT_CFG_ASLP) | (1 << INT_CFG_FF_MT));  // DRDY on INT1, ASLP_WAKE INT2, FF INT2
writeRegister(CTRL_REG5, readRegister(CTRL_REG5));

//SETUP THE MOTION DETECTION
writeRegister(FF_MT_CFG, 0xF8);     /*MOTION DETECTION AND LATCH THE
                                    //RESULT WHEN IT HAPPENS AS OPPOSED
                                    //TO COMBINATIONAL REAL TIME*/
    writeRegister(FF_MT_THS, mt);       //MOTION DETECTION THRESHOLDS
    writeRegister(FF_MT_COUNT, mdc);    //TIME MOTION NEEDS TO BE
                                        //PRESENT ABOVE THE THRESHOLD BEFORE INTERRUPT CAN BE ASSERTED

    MMA8452Active();
}


Interface Processing with Arduino to operate a servo by MouseX

When you try and solve a problem you want to focus on just one part at a time.  If I have understood what you are doing correctly then you are trying to:

Get a computer to talk to an Arduino over serial
Get an Arduino to position a servo
Get an Arduino to decode information sent by the computer
Get the computer to code the information
Get the computer to draw graphics.

You can try and ice a cake, feed a baby, talk on you mobile and drive a truck all at the same time, it doesn't mean its a good idea.  When you crash what was the cause?  You haven't got a clue, you were too busy trying to do all that not analyse what is happening at the same time.

So, what I'm trying to say is break it down.  Normally with motors the problem is related to power, people assume that the Arduino can provide enough power for a servo, that's not always the case.

I would:

Write a program that sets the servo to 10 hard coded positions.
Write a program that sets the servo to the position manually entered on the command line.
Write a program that draws the gradient, interprets the user entry and writes the command to be sent to the Arduino to the command line.
Write a program that runs on the Arduino and echoes what it receives over the serial line to some "other output mechanism"  (Connecting the computer via SoftwareSerial might be a good idea).

And once they are all working as you expect connect them all together and it will all magically work :)

(Sorry if I'm teaching you to suck eggs, if you have already done all this ignore me)


How to perform a data transfer to an external server

There is a good example of using the SubmitHttpRequest() in this article:
GPRS Shield SIM900 Arduino

You could easily modify:
mySerial.println("AT+HTTPPARA=\"URL\",\"www.yourwebsite.com/testing.php\"");

to include a string of the sensor value, and then using a PHP script to MySQL on your webserver. Maybe something like:
http://yourwebsite.com/testing.php?sensor1=5&sensor2=10


How to add if condition in RFID example?

As has been noted in the comments you can't compare arrays like that. Instead you have to iterate through each entry and compare the individual elements.

If it's just a few entries, then you can do it manually:

if ((uid[0] == 0xF0) && (uid[1] == 0x21) && (uid[2] == 0x5D) && uid[3] == 0xA7) {
    // ...
}

If your values are both in arrays then you can use the memcmp() function to compare them:

uint8_t compare[] = {0xf0, 0x21, 0x5d, 0xa7};

if (memcmp(uid, compare, 4) == 0) {
    // ...
}

memcmp returns 0 if the two arrays match up to the number of bytes given (4 in this case), or a negative or positive number if the one is "less than" or "more than" the other.


What's the relation between arduino standard library and esp8266 library?

The WiFi shield and an ESP8266 with any of several popular WiFi services firmwares are different pieces of hardware, each of which can provide WiFi services to another device connected to it, such as an Arduino Uno. Their interfaces are different, despite that they could be used to do similar jobs - offloading the WiFi communications from the Arduino - and the two libraries are written to drive each of them, respectively.


What programmer do I select in Arduino IDE for the ATMEL-ICE ISP?

As of V1.8.2, the ATMEL-ICE is now included as a programmer in the Arduino IDE.

The ATMEL-ICE was not available as a in-system programmer (ISP) in version 1.6.8 of the Arduino IDE.

On the 20th of Jan 2017, user facchinm added the ATMEL-ICE to the list of programmers in the IDE, and it was merged into the master on the 8th of Feb. It was released as a version on the 22nd of March 2017.


The string

"{\"AssetSensorDistance\":\"+st+\"}"

contains a literal "+st+". If you want to do string concatenation, you
should terminate the string with a double quote character, then add st,
then use another double quote to start the second part of the string:

"{\"AssetSensorDistance\":\""+st+"\"}"


Multiple upload/ Synchronization problem

Well, you can write a program that takes numbers out of Serial input.

int pin1 = Serial.parseInt();
int pin2 = Serial.parseInt();
// etc., etc.

Simple.


By default, the Serial print function shows only 2 decimals, however I'm sure the float has the full (unrounded) value, even if it does not show it.

You can read about it in the official documentation here

With the following code you can use more decimals (fragment from the official documentation):

-Serial.println(1.23456, 0) gives "1"
-Serial.println(1.23456, 2) gives "1.23"
-Serial.println(1.23456, 4) gives "1.2346"

Also, probably the next link (PrintFloat) will help:

PrintFloat

It works roughly by iterating through the digits and printing them.


Can't connect my ESP-12F to WiFi with my Arduino Uno

gpo0 goes to ground to program the module


Op Amp Understanding + Holiday Lights Tutorial

Per Jeremy Blum:

  If the input doesn’t have a audio input plugged in, then it’s said to be “floating” and you >can’t really count on the circuit to do what you would expect. The audio input connection >introduces a known voltage (0 when no sound is playing) connection between the positive op->amp input and GND that we then amplify. Try connecting the input to GND and you should see >the LED turn off.

Source: http://www.jeremyblum.com/2011/12/25/tutorial-14-for-arduino-holiday-lights-and-sounds/comment-page-2/#comment-1373392


View Arduino M0 SD card content on a computer

Yes, in at least some way, but what is realizable and best depends on a few things.

A traditional "card reader" is a USB Mass Storage device which basically exports the logical blocks of the card to the USB host computer.  While this is active, nothing on the embedded system may interact with the card.  The embedded system will need a USB device port which can operate in this mode, suitable software, and whatever data is recorded on the card will need to be a in a filesystem (FAT or whatever) that the host PC can read, and a data format in the files that existing or custom software for that PC can make sense of.
A different option would be to still store data on the card in a way that would be PC-compatible if the card were removed and placed in a PC, but not to be a USB Mass Storage device.  Instead, you might use the existing quasi-serial interface that is the typical role of an Arduino-type board's USB port, to send or summarize the data, either directly or by interpreting it first.  This could either flow into a simple terminal program, or into something custom.  Typically this means less work on the Arduino side, more but more work on the PC side.  Additionally, since there is never a direct export of the card's block, the embedded system continues to have access to the card the whole time, rather than having to surrender control of the card to the PC operating system as USB Mass Storage requires.
A variation of the above could leverage the fact that if only the Arduino ever reads the card for its own purposes or to report the data to a PC, it doesn't necessarily need to store things in a PC compatible file system, or even in a file system at all.


Resurrecting a fried Arduino (Bluno) USB port

Upload via ICSP. See those six pins next to the regulator you so expertly tacked on? Those are the ICSP pins. You'll need a second controller or programmer to do it.

http://arduino.cc/en/Tutorial/ArduinoISP


Do you have a image of this? Logically, and as far as I know, One wire will not carry both GND and Positive.

Are you talking of a DC jack kind of thing?

BTW, I'm starting out here too!


The STPM10 specification describes a SPI bus unlike any I have seen.  Apparently the STPM10 "SYN" line controls the direction of the "SDA" line.  As far as I know, there is no "SYN" line in a SPI bus.  As such I do not think a normal Arduino SPI library will talk to an STPM10.

A normal single port (MOSI and MISO combined) SPI slave would automatically switch between reading and writing bits.  When interfacing with a two port master (such as an Arduino) a resistor is used between the MISO and MOSI nets.

This is the best image I could find.  Ignore the chip names.  And substitute MOSI for SDO and MISO for SDI.  Note there is no "SYN" line in this SPI bus.

I'm showing this diagram as it appears the STPM10 is using a single line for both input and output data.

Because of the missing "SYN" line I do not think you can even use the SPI hardware in the Arduino's Atmel processor.  I think your only option is to create a SPI driver from scratch only using software.

I see where STMicroelectronics offers an evaluation software package that talks to the STPM10.  Guessing, it looks like they wrote it in National Instruments Lab View.  If you could get the source code for that it may provide hints on writing your own STPM10 driver.


First time set up- permission denied to usb port- ubuntu 14.04

From the documentation:

  Open Terminal and type:

ls -l /dev/ttyACM*

  you will get something like:

crw-rw---- 1 root dialout 188, 0 5 apr 23.01 ttyACM0

  The "0" at the end of ACM might be a different number, or multiple entries might be returned. The data we need is "dialout" (is the group owner of the file).

  Now we just need to add our user to the group:

sudo usermod -a -G dialout $USER

  then:

sudo chmod a+rw /dev/ttyACM0

  You will need to log out and log in again for this change to take effect.

Note that the preceding is old Ubuntu instructions. On modern distros that use ConsoleKit create the file /etc/udev/rules.d/01-ttyusb.rules containing the following and then reload the udev rules and replug the Arduino device:

SUBSYSTEMS=="usb-serial", TAG+="uaccess"


Connect the Sparkfun CAN bus shield with an RFduino

Ok, I found the solution. The fix first: I had to physically connect the reset line from the RFduino to the MCP2515 reset pin.
On page 55 in the datasheet of the MCP2515 it says that you can either reset it by pulling the reset line low or by sending a command over the SPI. The library I used is sending this reset command, but it isn't working for some reason. The logic analyser shows me this signal, it is the first recorded. Maybe it is a timing issue, that the reset has to be sent at the same time as the RFduino resets. Connecting the reset pin solves this issue, because then the RFduino and the MCP2515 are being reset at the same time.
If anybody knows more about this, feel free to tell me!


How to define function/macro so it is accesible throughout various cpp files

Have you thought of turning it into a small library?

libraries/StreamPrint/StreamPrint.cpp:

#include <StreamPrint.h>

void StreamPrint_progmem(Print &out,PGM_P format,...)
{
  // program memory version of printf - copy of format string and result share a buffer
  // so as to avoid too much memory use
  char formatString[128], *ptr;
  strncpy_P( formatString, format, sizeof(formatString) ); // copy in from program mem
  // null terminate - leave last char since we might need it in worst case for result's \0
  formatString[ sizeof(formatString)-2 ]='\0';
  ptr=&formatString[ strlen(formatString)+1 ]; // our result buffer...
  va_list args;
  va_start (args,format);
  vsnprintf(ptr, sizeof(formatString)-1-strlen(formatString), formatString, args );
  va_end (args);
  formatString[ sizeof(formatString)-1 ]='\0';
  out.print(ptr);
}

libraries/StreamPrint/StreamPrint.h:

#include <Arduino.h>

extern void StreamPrint_progmem(Print &out,PGM_P format,...);

#define Serialprint(format, ...) StreamPrint_progmem(Serial,PSTR(format),##__VA_ARGS__)
#define Streamprint(stream,format, ...) StreamPrint_progmem(stream,PSTR(format),##__VA_ARGS__)

Then in your code, wherever you want to use it:

#include <StreamPrint.h>

You can read more about writing libraries here: http://www.arduino.cc/en/Hacking/LibraryTutorial


What are possible issues when moving Arduino to another microcontroller?

There is NO best 8 bit or 16 or whatever bit uC (micro controller).
There always have been "better" ones and there always will be and better changes with your need as well as with time.

If you want or need a faster or more capable processor, use one.
For many tasks the existing AVR processors are very fine indeed.

A number of people are making Arduino-like uC's using ARM right now.
You can buy them 'off the shelf'.

Running "Arduino" code is where issues arise:
If you are willing to run 100% standard Arduino code applications will usually run well on the new uC.
If applications use precompiled libraries and you wish to use eg an ARM it will not run.
If you recompile the libraries and they are written in a compatible language flavor (C or whatever) then they MAY work for your new processor.
If they use assembler then they will not work in essentially all cases.

But, existing 'Arduino' hardware can use the high level language of your choice.
A new processor with a compatible compiler will compile eg C code that runs on Arduino hardware BUT port locations, register control methods etc need to be correctly allowed for.

It gets harder and harder as you try to fit the new giants into the old not-so-giant framework. Somewhere along the way it is easier to give up the attempt and use the Arduino for what it is good for and the 'new' processor where necessary.

Whatever the Arduino did well when new it still does well.

In most cases the speed, peripherals and memory capabilities are entirely fine for tasks that people who wish to use it wish to do.
The main issue is that an Arduino is not something it is not, just as a small family car is not a bus or a sportscar. Use the car where it is useful and use a bus or sportscar when necessary.


To read the pixels, start with this:

int32_t readNbytesInt(File *p_file, int position, byte nBytes)
{
    if (nBytes > 4)
        return 0;

    p_file->seek(position);

    int32_t weight = 1;
    int32_t result = 0;
    for (; nBytes; nBytes--)
    {
        result += weight * p_file->read();
        weight <<= 8;
    }
    return result
}

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

    Serial.print("Initializing SD card...");
    if (!SD.begin(53)) {
        Serial.println("initialization failed!");
        while (1); // <- this is how you should block execution, not with returns
    }
    Serial.println("initialization done.");

    // Open
    bmpImage = SD.open("Circle.bmp", FILE_READ);
    textFile = SD.open("test.txt", FILE_WRITE);

    int32_t dataStartingOffset = readNbytesInt(&bmpImage, 0x0A, 4);

    // Change their types to int32_t (4byte)
    int32_t width = readNbytesInt(&bmpImage, 0x12, 4);
    int32_t height = readNbytesInt(&bmpImage, 0x16, 4);
    Serial.println(width);
    Serial.println(height);

    int16_t pixelsize = readNbytesInt(&bmpImage, 0x1C, 2);

    if (pixelsize != 24)
    {
        Serial.println("Image is not 24 bpp");
        while (1);
    }

    bmpImage.seek(dataStartingOffset);//skip bitmap header

    // 24bpp means you have three bytes per pixel, usually B G R

    byte R, G, B;

    for(int32_t i = 0; i < height; i ++) {
        for (int32_t j = 0; j < width; j ++) {
            B = bmpImage.read();
            G = bmpImage.read();
            R = bmpImage.read();
            textFile.print("R");
            textFile.print(R);
            textFile.print("G");
            textFile.print(G);
            textFile.print("B");
            textFile.print(B);
            textFile.print(" ");
        }
        textFile.print("\n");
    }

    bmpImage.close();
    textFile.close();

    Serial.println("done write");
}`

Source: Arduino StackExchange Question: How to read bitmap image on arduino

The text output of this should be a file with an array of strings like R10G100B25, where R is the red component of the pixel, G is the green component and B the blue one. Work out how to print these to the serial output.

Note this is only compatible with the 24bpp format.


Arduino Leonardo(Atmega32u4) - Detecting if USB is connected to a computer?

ADDEN of UDADDR is set if the '32U4 has been assigned a USB address by the host and the firmware wants to enable USB connectivity.

UDADDR & _BV(ADDEN)


Why is my transistor getting very hot when controlling a 12V peristalic pump?

Measure the Current through the motor, the PN2222 can pass a maximum of 600mA.
I would guess that just over half an amp would be enough for the motor but you can check what you motor is trying to pull by connecting it to 12 V direct and measure the supply current.
The only thing that will make the transistor hot is excess current


Errors seen whilst compiling with AdaFruit Motor Shield ("invalid library")

Arduino IDE 1.6.6 and higher are picky about what you have in your libraries folders. There are two general valid library formats, the old "pre-1.5" format and the newer 1.5 format, the specification of which is at https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification.

Any folder in any of the Arduino libraries folder that doesn't follow a valid library format will cause the "Invalid library" message. Common causes of this issue are:

Putting a sketch folder in the libraries folder. Libraries may
contain example sketches but a sketch by itself is not allowed.
Libraries that are in a subfolder, rather than the library folder
being in the root of the libraries folder as required.

Now lets look at your specific messages:

Invalid library found in C:\arduino-1.6.8\libraries\Adafruit-Motor-Shield-for-Arduino-master: C:\arduino-1.6.8\libraries\Adafruit-Motor-Shield-for-Arduino-master

By looking at the Adafruit-Motor-Shield-for-Arduino repository we see that it's not a library but the PCB design files for the shield and thus has no business being in the libraries folder. Please move it to a different location.

Invalid library found in C:\arduino-1.6.8\libraries\robotarm: C:\arduino-1.6.8\libraries\robotarm

Without being able to see what's in this folder I can't say exactly the problem. If you will provide a directory listing I could update this answer with specific directions. As it is now, that folder is doing you no good in the libraries folder.


You have a couple of options, depending on how much you want to dive into electronics.

Find/buy a new powerbank that does not auto-shutoff
Find the current-sense resistor on the internal circuitry of your existing powerbank and change it out so that the device always thinks there is current flowing, or is more sensitive to your low-draw attachment. I was able to find a few websites describing this for specific powerbanks by searching.
Add a dummy load in parallel with your circuit, which wastes power, but does trick the powerbank into staying on.

It's also worth noting on the side, that you very likely do not have 50,000 mAh capacity in this powerbank, as others have noted. However, you ought to be able to get 16h of runtime with even a lower-rated powerbank if your claim of 60mA current draw is true.


There three ways to accomplish this. (last is my favorite)

1) Jumper an unused IO to the RESET pin. Leave it as INPUT for normal
    run, As it is externally pulled high. And when desired to reset set
    it as LOW and Output. (bang its rebooting).

setup() {
  ...
  pinMode(PINtoRESET, INPUT);    // Just to be clear, as default is INPUT. Not really needed.
  digitalWrite(PINtoRESET, LOW); // Prime it, but does not actually set output.
  ...                            // Does disable 10K pull Up, but who cares.

then when desired...

...
  pinMode(PINtoRESET, OUTPUT);   // lights out. Assuming it is jumper-ed correctly.
  while(1);                      // never gets here.

2) Jump to beginning of the code.

void(* resetFunc) (void) = 0;  // declare reset fuction at address 0
...
resetFunc(); //call reset

But be careful, this does not perform a true reset, in that all the registers ARE NOT DEFAULTED. Rather they and the IO are left as is. Where somethings from the bootloader and then the heap will be initialized. And reset are not!

3) Use the watchdog. The SoftReset library makes it easy. Although it is not difficult to implement directly. Shown below..

#include <avr/wdt.h>
...
setup() {
  ...
  MCUSR = 0;  // clear out any flags of prior resets.
  ...

then when desired...

...
wdt_enable(WDTO_15MS); // turn on the WatchDog and don't stroke it.
for(;;) {
  // do nothing and wait for the eventual...
}
...


That is not easy to do. You could try diodes and mosfets as switches, but one way or the other, there will probably some leakage current. The 6N137 requires power for the receiving signal.
Other common optocouplers might have leakage current in the nA range for the transistor output. That might be possible. Connect the GNDs. The RX and TX via optocouplers. DTR to RESET with 100nF as usual. Maybe you don't need extra inverters when the transistor outputs are used as emitter followers.

Could you make your project with the ATmega328P without the usb-to-serial module ? The Arduino Pro Mini does not have a usb-to-serial either.
Now that I mention the Arduino Pro Mini: Instead of making an Arduino compatible circuit with a ATmega328P, you could also buy a Arduino Pro Mini 8MHz, and remove the voltage regulator and the power led. Then you have the same thing.

That breadboard Arduino tutorial has +5V connected to AREF. Please don't do that. Keep AREF open, or connect a capacitor of 100nF to it to reduce some noise for analogRead.

In the deepest sleep mode, the ATmega328P can run more than a year on three AA batteries. The timer of the WatchDog can be used to wake up.
The voltage of the three AA batteries is directly connected to the VCC of the ATmega328P, without voltage regulator.

A very good tutorial about power saving is this: Nick Gammon about power saving


Don't do that. Converting a time to double is highly inefficient.
Moreover, your approach suffers from a rollover issue every 24h.

If you just want to compare the time of day with 8:30, you can do it in
a very straightforward way:

if (now.hour() > 8 || (now.hour() == 8 && now.minute() >= 30))

If the long if annoys you, you can put the comparison logic inside a
static inline function. If you really want to combine hour and minute
into a single number, then convert to an integer rather than a double:

if (now.hour() * 100 + now.minute() >= 830)

This can be made more efficient if you think in binary rather than
decimal: you can build a 16-bit number with one byte holding the hours
and the other byte holding the minutes:

if ((now.hour() << 8) | now.minute() >= (8 << 8) | 30)

Again, you may encapsulate the ((a)<<8|(b)) in a macro or static
inline function if it helps with readability. If you want to compare to
an absolute time, your best option is to build a DateTime object
representing the deadline, and compare with now as:

// Assume timeout should be today at 8:30.
DateTime timeout(now.year(), now.month(), now.day(), 8, 30, 0);
if (now.secondstime() >= timeout.secondstime())

Here the secondstime() method is used to convert the DateTime into a
scalar number (a 32-bit integer of type time_t) that can be easily
compared and is far more efficient than using floats.


If you can estimate speaker power, it probably is reasonable to use the ordinary power formula P = I²R for estimating the current the relay needs to handle.  Typically, high-power speakers of a given kind are bigger than low-power speakers of the same kind.  But as you can see from pictures of
5W,
10W, and
40W speakers, some 10W speakers are smaller than some 5W speakers, and some are bigger than 40W speakers, so power estimation based on speaker size can be difficult.

If you have access to the sound source (tuner or player or whatever, connected to an amplifier) you may find output power listed on the amplifier.

In any case, due to the I² term in the power formula, the range of current to plan for is relatively small.  For example, if 5W is going to an 8Ω speaker, 5/8 = I², and I =  0.79 A.  If it's 40W, then I = 2.24 A.  This range is likely to be handled ok by relays sold for ordinary use with Arduino systems.

Note 1: A relay's current rating ordinarily is derated significantly when the relay is used to switch DC or high-voltage AC.  Audio is low-voltage AC and relay derating probably isn't needed.  Note 2: The current a relay can safely switch in a live circuit may be much less than the unswitched current that closed contacts can carry.  This might not be a problem with low-voltage audio.  Note 3: Some commercial high-wattage audio distribution systems operate at higher voltages (see, eg, wikipedia's high-voltage audio distribution systems article, re 70.7 V etc systems); if you have one of those – as amplifier labeling might reveal – the example calculations shown above would need adapting.


create a struct and store the struct

#include <EEPROM.h>

const int DATA_ADDR = 0;

struct MyData {
  float temperature, differential, calibration,hta,lta,hha,lha;
};

MyData data;

void setup() {
  data.temperature = 1.2;

  EEPROM.put(DATA_ADDR, data);

  EEPROM.get(DATA_ADDR, data);
}

void loop() {

}


Algorithms to reduce measurement error from analogue sensors

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.


You are comparing a char* to a char*. Array's are contiguous memory locations and the variable name for an array in this case command_1 and incomingPacket point to the first element in the array. Since they are two different array's, the location of the first element in command_1 is different than the location of the first element in incomingPacket so command_1 will never equal incomingPacket.

In order to check if the incoming packet equals "Foo" try

if(strcmp(incomingPacket, "Foo") == 0)

This utilizes the strcmp() compares two null terminated character arrays and returns 0 if they are equal.

Just ensure that the incomingPacket is null terminated I have never worked with this library before.


How does the Arduino send more than 6 bytes via I2C

There is no reason to believe there is a 6 byte limit.

The Arduino Reference makes no mention of a 6 byte limit.

The Wire.cpp defines 'txBuffer[BUFFER_LENGTH];' where BUFFER_LENGTH = 32 (defined in Wire.h). The maximum is 32 bytes, just as you noticed.


Arduino is not responding to a Tiny RTC I2C modules, How to fix?

You have a couple of problems (although the lack of pull-up resistors is not one of them, because the board you linked has pull-up resistors on it).

The DS1307 needs to operate at a minimum of 4.5 volts, so you can't connect it to the 3.3V pin on the Due. (You need to supply it with 5V).
However the Due is a 3.3V device on its data pins, and thus you can't connect the DS1307 directly to SDA/SDL or you will damage the Due.

Thus you need to supply the clock board with 5V, and use a bi-directional logic-level converter, such as this (using two logic-level MOSFETs):

You can buy level-converter boards, but as you can see, one is easy enough to make up.

Now the clock chip runs at 5V, but the logic levels are converted to 3.3V for the Due.

I tested this with mine, and it worked OK.

#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 myclock;

void setup () {
    Serial.begin(115200);
    Wire.begin();
    myclock.begin();
}

void loop () {
    DateTime now = myclock.now();

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(' ');
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

    Serial.print(" since midnight 1/1/1970 = ");
    Serial.print(now.unixtime());
    Serial.print("s = ");
    Serial.print(now.unixtime() / 86400L);
    Serial.println("d");

    Serial.println();
    delay(3000);
}

Output:

2016/3/6 12:0:20
 since midnight 1/1/1970 = 1457265620s = 16866d

2016/3/6 12:0:23
 since midnight 1/1/1970 = 1457265623s = 16866d

2016/3/6 12:0:26
 since midnight 1/1/1970 = 1457265626s = 16866d

A useful technique for debugging is to run the "I2C scanner" I have on my I2C page. The code is:

// I2C Scanner<!-- language-all: lang-none -->
// Written by Nick Gammon
// Date: 20th April 2011

#include <Wire.h>

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

  // Leonardo: wait for serial port to connect
  while (!Serial)
    {
    }

  Serial.println ();
  Serial.println ("I2C scanner. Scanning ...");
  byte count = 0;

  Wire.begin();
  for (byte i = 8; i < 120; i++)
  {
    Wire.beginTransmission (i);
    if (Wire.endTransmission () == 0)
      {
      Serial.print ("Found address: ");
      Serial.print (i, DEC);
      Serial.print (" (0x");
      Serial.print (i, HEX);
      Serial.println (")");
      count++;
      delay (1);  // maybe unneeded?
      } // end of good response
  } // end of for loop
  Serial.println ("Done.");
  Serial.print ("Found ");
  Serial.print (count, DEC);
  Serial.println (" device(s).");
}  // end of setup

void loop() {}

If you don't see your device appear in the Serial Monitor, there is no point wondering why the date doesn't change, because it hasn't found the clock at all. You should see something like this:

I2C scanner. Scanning ...
Found address: 104 (0x68)
Done.
Found 1 device(s).

How the level converter works

For more information, read the Philips Application Note AN97055

In brief (taking SDA as an example):

If neither side is driving SDA low, then VGS is zero (they are both 3.3V) and the MOSFET does not conduct. Hence each side is "pulled-up" to their respective voltages. The low side is pulled up to 3.3V and the high side is pulled up to 5V.
If the low side drives SDA low, then VGS is 3.3V which is high enough for the MOSFET to conduct. Since it conducts it also drags the high side low as well (overpowering the 10k pull-up resistor).
If the high side drives SDA low, current initially flows through the drain substrate diode of the MOSFET (it will be a diode drop above 0V, namely 0.7V), lowering the voltage at the source, until VGS is high enough for the MOSFET to conduct. Once it starts conducting then the low side is pulled further lower.

  Do you have an actual photograph of this?

I've pulled it all apart days ago, however thankfully I took a snapshot before I did.

To be honest, the schematic is easier to follow. When looking at photos it can be hard to see exactly what is plugged into where.


There are a number of common solutions to "not enough pins".

Reduce the number of pins you need. This option is often discarded out of hand, but may be the best. For example, you may be able to reduce the 18 individual pins for the on/off capacitive sensor, with a different part, which may be able to give you an X,Y co-ordinate of where it is touched, with fewer pins.
Multiplex the pins. This seems to be the most likely to work in this case - you will use (for example) 9 Uno pins to power the LED and capacitive sensor on each cell, one at a time. So, for example, you might attach D1 to the top left cell, D2 to the top-center, and so forth. Then you use another pin (e.g. D10) to connect to ALL the cathodes of the LEDs (via a single transistor, to protect the Uno from too much current), D11 and D12 to connect to one of the data pins of ALL of the capacitive sensors. So, you "select" cell one, by switching D1 from LOW to HIGH. Then, you put D10 to LOW, so current will from across the LEDs. Read the capacitive sensor, which is now also powered on. Although all of the censors are connected to D11 & D12, only one will be powered on, so you will only be reading that one. Once read, you probably want to delay a few milliseconds, to make sure the light shows up. Then move on to the next cell. Go round and round all cells. The LEDs will be off 8/9ths of the time, but it will still be visible. NOTE: reading more about capacitive sensors, I see that one is input, the other output. You would need a transistor for each of the "select" pins, used as a switch to connect D11 to the correct sensor.
Do the same thing, but using a decade counter. Connect 2 pins from the Arduino to the decade counter - one to "count", and one to reset. First, strobe the reset - this will set the first output of the decade counter high - connected to cell 1. Then, when you want to move to the next cell, drop the "count" low, then high again. You are now on the next cell. Repeat until you get to cell 9, then send the "reset" (which guarantees you know where you are up to) to get back to cell 1.
Charlieplexing (mostly suitable for output only). This is a somewhat complicated, but very efficient (pin-count wise) way of running lots of LEDs off only a few Arduino pins, by using them in combination. For example, 3 pins could run 6 LEDs - if you have pins A, B and C, run one LED from A to B, one from B to C, and one from C to A; then, run 3 more LEDs in the OPPOSITE direction (don't forget your resistors!). Depending on which LED you want lit, you might want pin A high, B low, and C high impedance (INPUT). 4 pins will get you 12 LEDs, 10 will get you 90 LEDs. If you think this might be useful, check out the Wikipedia
Use chips that are designed specifically for the application you need. For example, TLC5940 chips will run up to 16 LEDs each, controlling the brightness of each LED independently. You set the brightness of each LED, then let the TLC5940 take care of the work. SIPO chips such as the 74HC595 (8 outputs) are similar, but only allow "on" or "off" for each pin. Both of these can be "daisy chained" - with the same number of Arduino pins, you can connect the output of one to the input of the next, to control more outputs.
Use multiple Arduinos. Yes, this might sound expensive, but you can use an AtMega (e.g. AtMega328, which is the same chip used in the Arduino) for a fraction of the cost. You might even use an AtTiny - even cheaper (but less memory). All of these can run the same code. This is the most flexible, but is also the most work - you would need to think about which chip does what, how they interact, and how they talk to each other. This also has the advantage that, rather than a chip that runs at 16mhz, you can now have multiple chips that each run at that speed, and have more memory each. Some applications work well with one "master" chip controlling one (or more) "slaves", whereas other applications work really well as peer-to-peer, either with each node running the same code, or each doing their own thing, and passing information to other nodes. For this example, you might use one AtTiny85 for each of the 9 cells, with an Arduino to be the master. Or, use an AtTiny84, for each row of 3 cells, with one Arduino to rule them all. The AtTiny84 has 14 pins: power, ground, reset, and 11 data pins - 2 is enough for a shared data bus, such as i2c, leaving 3 pins for each of 3 cells.
(not relevant for this example) For multiple on/off sensors (e.g. pushbuttons, switches), you can attach them through different values of resistors, and connect them to an ADC pin as a voltage divider. For example, connect ground via R0 to an analog pin; then connect to the same pin: pin -> resistor 1 -> pushbutton 1 -> +5v; pin -> resistor 2 -> pushbutton 2 -> +5v, and so forth. Build the circuit, and test each combination of switches/pushbuttons on/off, what the output will be. Then, in your code, figure out which combination it is closest to. Each resistor will need to be different resistance. If you only expect one switch to be on at once, it's a lot easier.


Seeing all on for 128+ and all off for 127- is indicative that you are using a pin that can't do PWM.

If you use a non-PWM pin with analogWrite it goes "Is this less than 128? Yes? Then I will turn it off. Otherwise I will turn it on.".

case NOT_ON_TIMER:
default:
    if (val < 128) {
        digitalWrite(pin, LOW);
    } else {
        digitalWrite(pin, HIGH);
    }

Since you don't mention what board you are using I can only assume that you have picked a pin that can't do PWM. Change to a pin that can do PWM and you should get a PWM signal.


Arduino Yun not showing anything on the serial monitor

Assuming the code works, you should be able to change the position of the servo by altering the initialized color values.  Currently they are:

 const int redPos = 160;
 const int orangePos = 130;
 const int yellowPos = 100;
 const int greenPos = 70;
 const int bluePos = 30;
 const int nonePos = 0;

If, for example, the positions of Red and green are to be swapped all that is needed is to alter the code like this:

 const int greenPos = 160;
 const int orangePos = 130;
 const int yellowPos = 100;
 const int redPos = 70;
 const int bluePos = 30;
 const int nonePos = 0;

The numbers, according to the Arduino's servo driver web page, are the angle in degrees the servo will be moved to after executing the call to the Arduino servo driver.

Given the above, if a new color violet were to be added to the original set of colors the first change would be to move the servo positions slightly higher to make room for the new color.

 const int redPos = 160;
 const int orangePos = 135;
 const int yellowPos = 110;
 const int greenPos = 85;
 const int bluePos = 60;
 const int violetPos = 35;
 const int nonePos = 0;

The next change would be to alter the ranges of the color test code.  As you did not specify what hardware you are using to detect colors, you will have to experiment to find the combination of red, green & blue which matches the new color violet.  The code used for detecting blue is:

 else if ((r < 0.8) && (g < 1.2) && (b > 1.2))

Likely violet contains more red and may be detectable with a line of code like this:

 else if ((r > 1.0) && (g < 1.2) && (b > 1.2))

The position of this test may be important depending on how the detector works.  It may be best to place it after testing for orange.  Remember to use the new initialized variable such that you code may look like this:

else if ((r > 1.0) && (g < 1.2) && (b > 1.2)){
  Serial.print("\tVIOLET");
  myservo.write(violetPos);
}


Differing Serial Values Between Arduino Uno and TTGO ESP32 SX1276

Do different boards analogRead differently?

Yes.

Your typical Arduino has a 10-bit ADC. That can give values between 0 and 1023 (210-1), with 400 falling just short of half way.

The ESP32 has a 12-bit ADC. That gives values between 0 and 4095 (212-1), which means that your 2000 falls, yes, just short of half way.

It is not the value from the ADC that is important - it is what the value represents. It is meaningless until you convert it into something meaningful, like a voltage.

Like asking "How heavy is it?" -- "It's 23." Completely meaningless, until you qualify it with units, and the units are different because of the different resolutions, so you need to "convert" it into units that have a meaning.

Typically the value represents a proportion of the supply voltage (but not necessarily: it's actually a proportion of the ADC reference voltage, which is often the same thing as the supply voltage).  On the Arduino the value is 1/1024th of the supply voltage. On the ESP32 it's 1/4096th.


More speed from ATMEGA328 Internal Clock

shiftOut() relies on digitalWrite(), which is dead slow by AVR
standards. You could probably get a factor 5, or even 10, by
reimplementing shiftOut() using direct port
access instead.
Using SPI (as suggested in the comments) would be even faster, but you
would need to clock out of pin 13.

Edit: here is an attempt at such implementation. Note that it is
completely untested. Note also the small delay meant to avoid the thing
being too fast. You may try to play with the delay value.

#include <util/delay.h>

/*
 * Especialized and faster shiftOut().
 * This assumes no one is touching PORTB at the same time.
 *
 * dataPin = 11 (PB3), clockPin = 12 (PB4), bitOrder = MSBFIRST.
 */
void myShiftOut(uint8_t val)
{
    for (uint8_t i = 0; i < 8; i++)  {
        // Send data bit.
        if (val & 0x80)
            PORTB |= _BV(PB3);
        else
            PORTB &= ~_BV(PB3);
        val <<= 1;

        // Toggle clock twice.
        PORTB |= _BV(PB4);
        _delay_us(0.5);
        PORTB &= ~_BV(PB4);
    }
}


Using Multiple 4 Digit displays with the same pins

That is an SPI interface.  Using multiples should be easy.  Each one has a CS pin.  When that pin is pulled low it selects that chip as the one you are talking to.  Several displays could all share the CLK, DIN, and DOUT pins on the Arduino and each would have it's own pin on the Arduino for CS.  To update any given display, you pull its CS pin low and then transmit your data.  If you pull the CS pins on two displays low at the same time you'll send the data to both.  Whichever has the CS pin pulled low on it is the one that listens.

Google SPI and do a little investigation on SPI with Arduino.  That will help you learn a little about how SPI works and you will certainly get your question fully answered about how to drive multiple chips while sharing pins.  Driving multiple things with the same pins is the whole point of SPI.

The connection would look like this for an UNO -

Pin 13  ----  CLK pin on all chips

Pin 12  ----  DOUT on all chips

Pin 11  ----  DIN on all chips

Choose a different pin on Arduino for each chip and connect to the CS pin.

To use SPI, pin 10 MUST be configured as an output.  It cannot be an input.  So it would be a good idea to use 10 for one of the CS pins just to make sure it is going to stay an output.

EDIT:

I just looked at the page you linked to and it looks like the library you are using isn't using the SPI hardware but is bit-banging SPI from software using other pins.  The concept is still the same, all share CK and DIN and the CS pin picks the one you're talking to.

The code would be a lot faster and much more compact if you changed this library to use the SPI hardware instead of software.  It just limits which pins you have to use to the ones I listed above.

EDIT AGAIN:

I feel generous and it was really really really easy to do so I switched his code to run on the SPI hardware.  It compiles but hasn't been tested.  It should work though.  Hooking DOUT to pin 12 is optional, but you still can't use pin 12 for anything else so you might as well.

PT6961_SPI.h

/*
  PT6961.h - Library for communicating with PT6961 LED driver.
  Created by Garrett Blanton January, 16, 2013.
  Released into the public domain.
*/

#ifndef PT6961_SPI_H_
#define PT6961_SPI_H_

#include "Arduino.h"
#include <SPI.h>

class PT6961
{
  public:

    PT6961(uint8_t CS);
    void initDisplay();
    void initRAM();
    void sendCmd(char cmd);
    void sendDigit(char digit, char val);
    void sendNum(int num, char colon);
    void sendDigits(char digit1, char digit2, char digit3, char digit4, char colon);

    const static char _DISPLAY_6X12 = 0x02;
    const static char _DISPLAY_7X11 = 0x03;
    const static char _AUTO_INCREMENT = 0x40;
    const static char _FIXED_ADDRESS = 0x44;
    const static char _DISPLAY_OFF = 0x80;
    const static char _DISPLAY_1_16 = 0x88;
    const static char _DISPLAY_2_16 = 0x89;
    const static char _DISPLAY_4_16 = 0x8A;
    const static char _DISPLAY_10_16 = 0x8B;
    const static char _DISPLAY_11_16 = 0x8C;
    const static char _DISPLAY_12_16 = 0x8D;
    const static char _DISPLAY_13_16 = 0x8E;
    const static char _DISPLAY_14_16 = 0x8F;

  private:

    uint8_t _CS;

};

#endif

PT6961_SPI.cpp

/*
 PT6961.cpp - Library for communicating with PT6961 LED driver.
 Created by Garrett Blanton January, 16, 2013.
 Released into the public domain.
 */

//0 - A
//1 - B
//2 - C
//3 - D
//4 - E
//5 - F
//6 - G
//7 - Colon
#include "Arduino.h"
#include "PT6961_SPI.h"

PT6961::PT6961(uint8_t CS) {

    pinMode(CS, OUTPUT);
    _CS = CS;

    SPI.begin();
    SPI.setBitOrder(LSBFIRST);

}

void PT6961::initDisplay() {
    sendCmd(_DISPLAY_6X12);
    sendCmd(_AUTO_INCREMENT);
    initRAM();
    sendCmd(_DISPLAY_14_16);
}

// Initializes RAM to all zeros
void PT6961::initRAM() {
    //first clear 8 bytes of the display RAM
    digitalWrite(_CS, LOW);
//  shiftOut(_DIN, _CLK, LSBFIRST, 0xC0);
    SPI.transfer(0xC0);
    for (int i = 0; i < 8; i++) {
//      shiftOut(_DIN, _CLK, LSBFIRST, 0x00);
        SPI.transfer(0x00);
    }
    digitalWrite(_CS, HIGH);
}

// Use to send command based on enumeration
void PT6961::sendCmd(char cmd) {
    digitalWrite(_CS, LOW);
//  shiftOut(_DIN, _CLK, LSBFIRST, cmd);
    SPI.transfer(cmd);
    digitalWrite(_CS, HIGH);
}

void PT6961::sendDigit(char digit, char val) {
    digitalWrite(_CS, LOW);
//  shiftOut(_DIN, _CLK, LSBFIRST, digit);
//  shiftOut(_DIN, _CLK, LSBFIRST, val);
    SPI.transfer(digit);
    SPI.transfer(val);
    digitalWrite(_CS, HIGH);
}

void PT6961::sendNum(int num, char colon) {
    int digit1 = num / 1000;
    int digit2 = (num % 1000) / 100;
    int digit3 = (num % 100) / 10;
    int digit4 = (num % 10);

    sendDigits(digit1, digit2, digit3, digit4, colon);
}

void PT6961::sendDigits(char digit1, char digit2, char digit3, char digit4,
        char colon) {

    const char DISP[17] = { 0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07,
            0x7f, 0x6f, 0x77, 0x7c, 0x58, 0x5e, 0x79, 0x71, 0x61 };

    digitalWrite(_CS, LOW);
//  shiftOut(_DIN, _CLK, LSBFIRST, 0xC0);
    SPI.transfer(0xC0);

    if (colon == 1) {
//      shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit1] | 0x80);
        SPI.transfer(DISP[digit1] | 0x80);
    } else {
//      shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit1]);
        SPI.transfer(DISP[digit1]);
    }

//  shiftOut(_DIN, _CLK, LSBFIRST, 0xC2);
    SPI.transfer(0xC2);

    if (colon == 1) {
//      shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit2] | 0x80);
        SPI.transfer(DISP[digit2] | 0x80);
    } else {
//      shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit2]);
        SPI.transfer(DISP[digit2]);
    }

//  shiftOut(_DIN, _CLK, LSBFIRST, 0xC4);
    SPI.transfer(0xC4);
//  shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit3]);
    SPI.transfer(DISP[digit3]);
//  shiftOut(_DIN, _CLK, LSBFIRST, 0xC6);
    SPI.transfer(0xC6);
//  shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit4]);
    SPI.transfer(DISP[digit4]);
    digitalWrite(_CS, HIGH);
}

Example.ino

#include "Arduino.h"
#include <SPI.h>
#include "PT6961_SPI.h"

PT6961 LED(10);   /// This is the pin number for CS pin on each chip
// PT6961 LED2(9);  // The next might look like this if it were connected to pin 9
void setup()
{
     LED.initDisplay();
     Serial.begin(9600);
}

void loop()
{
     //count through 0-9,a-f
     for(int i=0; i<16; i++)
     {
          LED.sendDigits(0,0,0,i,0);
          Serial.println(i);
          delay(500);
     }
}


Is possible to process analogue inputs with variation frequencies in MHz?

Your typical ATMega-base Arduino cannot sample anywhere near that kind of speed.

It takes 13 clock cycles to sample an analog value on an ATMega chip, and the maximum clock frequency for the ADC is 1MHz. That gives you an absolute maximum sampling speed of 76923 samples per second. That means the highest frequency you can sample is 38461Hz.

There are better chips on the market with higher sampling speeds, but they aren't Arduino. Some can sample at the tens of millions of samples per second allowing you to sample frequencies in the low MHz. Other specialised ADC chips are available that can sample in the Gsps range which are what are used in oscilloscopes and high speed communication (fibre optic) systems etc. Working with these kind of chips needs quite a lot of skill though as the analog signal paths requires special design and consideration.

Also when sampling at those kind of frequencies you need a lot of high-speed memory, which no Arduino can ever even consider the possibility of having.


ADXL345 I2C setup not returning anything

You may have damaged the chip with 5 V already. Sparkfun didn't include a regulator in their breakout. Your pull-ups are also too small; significant current flows when the I2C lines are pulled low. Use two 4.7k or 10k resistors instead. Assuming your Redboard is just like the Uno, connect pin 2 to the INT1 pin of the breakout, to make use of the interrupt capabilities. You also need to call attachInterrupt() and register a handler.

However, you bought this module from Sparkfun, as well as your Redboard. You should first follow their tutorial and library before trying any others. Theirs is SPI-based though. If you must use I2C, try out the Adafruit library.


Arduino UNO IR blaster - storing codes in PROGMEM

The Arduino Uno can not read data from PROGMEM (data in flash memory) in the same way as reading data from ram, there are special functions to read data from PROGMEM.

Create a buffer in ram and use one of those special functions to copy the data into that buffer.

Start with the Arduino PROGMEM reference.
Nick Gammon had made a great tutorial about PROGMEM.
All the PROMEM functions are in <avr/pgmspace.h>

Is the array of numbers always the same length ? That would make the sketch a lot easier.

Then perhaps something like this:

const unsigned int irTable[9][67] PROGMEM = { { ... }, { ... } }

unsigned int irBuf[200];

i = ...   // number of command
memcpy_P ( irBuf, &irTable[i][0], 67 * 2);
irsend.sendRaw (irBuf, 67, ...);


That little blue wire on your breadboard is shorting out the motor. You have most likely now blown the transistor and maybe your power supply. The 12V may also now have made its way into the Arduino through the dead transistor and nuked the rest of it.

Alternatively, the massive base currents imposed by the shorted ground connection may have burned out parts of the Arduino.


Connection between ATTiny85 and RaspberryPi3 with nRF24L01+

As Mikael Patel pointed out, my MOSI and MISO pins were switched.

On the pinout for the ATtiny85, the MOSI and MISO pins are for when the chip is a slave (i.e. programming). DO and DI and used for output as SPI master.


Serial Communication Issue with Telit LE910 LTE Modem

First, please don't post screen images.  Just select the text and paste it into your questions.  You can copy code from the editor or messages from the Serial Monitor window.  Paste into your post, select the section again, and press ctrl-K to format it as a code block in your question (like below).

  Am I doing something wrong with reading the Serial information from the modem?

Yes, you are using delay to "wait" for the response to appear.

  Am I hitting a timeout of some sort?

In a way.  The input buffer only has room for 64 characters.  If you don't read any of them because you're blocked at a delay statement, the 65th character (and all others) will be ignored.  These answer your specific questions.

Further Suggestions:

To fix the real problem, not just the symptoms, you will have to change your sketch structure.

There are many ways to implement this in a non-blocking way (i.e., without using delay).  I prefer Finite-state Machines; there are many good tutorials for this  technique (e.g., Nick Gammon's site).

Although it's not as flexible, you could also use your own while loop for each response, with a timeout.  Here's a simple example that reads one line.

char resp[20];
char resp_Len = 0;
const uint32_t TIMEOUT_MS = 5000UL; // 5 seconds

AltSoftSerial modem_port; // pins 8 & 9 ONLY

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

void loop()
{
  uint32_t startTime = millis();
  while (millis() - startTime < TIMEOUT_MS) {
    if (modem_port.available()) {
      char c = modem_port.read();
      if (c == '\n') {
        resp[ respLen ] = '\0'; // NUL terminate
        respLen = 0; // reset for another line
        break;

      } else if (respLen < sizeof(resp)-1) { // Room for more?
        resp[ respLen++ ] = c; // accumulate one more character
      }
    }
  }

  Serial.print( F("Response = '") ); // F macro saves RAM
  Serial.print( resp );
  Serial.println( '\'' );
}

But when the response is long (hundreds of bytes), you may not have sufficient RAM to save the whole response, and then parse it.  You MUST use an FSM to parse the bytes as they are received.

For your application, you should skip all the stuff at the front and watch for the "Content-type:" pattern and the two newlines, then save the next line (as above) for parsing:

enum state_t { SKIP_TO_CONTENT_TYPE, SKIP_TO_EMPTY_LINE, SAVING_TIMESTAMP };
state_t state = SKIPPING
uint8_t index = 0;

const char ContentType[] = "Content_type:";

bool watchForTimestamp()
{
  if (modem_port.available()) {
    char c = modem_port.read();

    // Handle this one character, based on our current "state"

    switch (state) {
      case SKIP_TO_CONTENT_TYPE:
        if (c == '\n')
          index = 0;

        else if ((index < sizeof(ContentType) && (c == ContentType[ index ])) {
          // next char matches
          index++;

          if (index == sizeof(ContentType)) {
            // All matched!
            state = SKIP_TO_EMPTY_LINE;
            index = 0;
          }
        }
        break;

      case SKIP_TO_EMPTY_LINE:
        if (c == '\n') {
          index++; // this counts newlines since "Content-type:"

          if (index == 2) {
            state = SAVING_TIMESTAMP;
            index = 0;
          }
        }
        break;

      case SAVING_TIMESTAMP:
            ... Hint: something like the line-saving technique above.
        if (something) {
          return true;
        }
        break;
    }
  }

  return false;
}

Some part of loop will just call waitForTimestamp over and over:

void loop()
{
    ...

  bool gotResponse = false;
  state = SKIP_TO_CONTENT_TYPE;

  while (millis() - startTime < TIMESTAMP_TIMEOUT) {
    gotResponse = waitForTimeStamp();
    if (gotResponse) {
      // parse the timestamp from the resp array
         ...
      break;
    }
  }

  if (gotResponse) {
    Serial.print( F("Timestamp = ") );
    Serial.print( resp );
    // now you can parse the small response array
       ...

  } else {
    Serial.println( F("Didn't receive timestamp!") );
     ... other error code
  }
}

This may be a "main" FSM for loop, with a nested FSM for parsing the HTTP response.  The rest is up to you.  :)

BTW, SoftwareSerial is very inefficient.  It cannot send and receive at the same time, and it disables interrupts for long periods of time.

If you can use pins 8 & 9, you should use AltSoftSerial instead.  It is very efficient.

If you can't switch to those pins, you could use NeoSWSerial if the modem is running at 9600, 19200 or 38400.


Weird effect of AVR C on USB-serial communication

By defining your own main() you are circumventing the Arduino startup procedures.
Normally with Arduino code main() first runs an init() function before setup() and (repeatedly) loop().  This init() function will configure, amongst other things, the timer for millis() and delay().
This is the normal main() for a basic AVR-based board:
int main(void)
{
    init();

    initVariant();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}

It first initializes common functions, then board-specific ones (normally nothing), and if applicable, the USB interface (for ATMega32U4 based boards, like the Leonardo).
Only then does it go on to run your sketch.
If you want to use both your own main() and Arduino functions like delay() then you will have to call those initialization routines before running the rest of your code.


HID is a strange beast to get your head around.
It operates by way of "Report Descriptors". These are "maps" that lay out what the values you send mean. It's these descriptors that make a keyboard a keyboard and a mouse a mouse.
When you use Keyboard.h you attach a Keyboard report descriptor to the USB HID endpoint, and the computer knows to interpret the data coming in as keypresses. When you use Mouse.h you attach a Mouse report descriptor and the computer knows to interpret the data coming in as mouse movements and button presses.
If you want your computer to ignore the data that you send and allow your own program to be able to receive the raw data instead then you need to use a descriptor that the computer doesn't recognise. In such a case it just ignores the data.
There's a "Raw HID" library for Arduino that does that - it uses a "blank" report descriptor that just gives you a plain 64 byte block of data to do what you want with.
There's a good HID library by Nico Hood that implements the raw mode (as well as others).
For receiving the data on your computer you will have to have your program directly interface with the USB HID system. There's plenty of libraries for most languages to do this for you (hidapi in C / C++, hid in Python, hid4java for Java, etc).


Reading and Writing to a JSON File on the Desktop from Arduino?

The Arduino cannot access files on a desktop computer.
However you can write software on your computer (you already use Python, so why not use that?) to accept information over Serial, process it, and store it in any way you like (including JSON), or return data from the computer to the Arduino if needed.


Firstly you should be including TimeLib.h not Time.h - the library header name has been changed to avoid conflicts on case-insensitive systems (Windows) and the internal time.h header in many compilers.

Secondly you should always include all your libraries in your INO file directly.  This is because the IDE parses the INO file before compiling looking for any included libraries. It then adds these found libraries to the list of libraries that need to be compiled. Without this you won't get the source code for your libraries compiled properly.


I found the problem. I could see that the false value is the character code of the minute I am displaying. I display hours and minutes and there was a declaration that was 3 characters short for the string I got as a result for hours added to minutes. Yes, it was memory corruption. So be very careful to dimension enough places for your C-strings including 1 extra for 0. If you are not so short on RAM then a few more characters will do no harm, the end of the string will be the character before the 0 in memory.
When strange things happen start looking at this matter!


Error uploading Arduino Micro Sketch using Kubuntu

Therefore I tried the newest version of the Arduino software from the arduino homepage.

  The package version I am using is 1:1.0.5+dfsg2-2, the other I tried was 2:1.0.5+dfsg2-4.

That is not the newest version.

I think the more recent versions of the IDE are more robust - after all they have fixed reported bugs. Try 1.6.5 or 1.6.7. The version 1.0.5 is pretty old.

I too have had "upload completed" on my Leonardo (virtually the same as the Micro) when it did no such thing.

I am using Ubuntu 14.04 and don't have any problems programming my Micro with IDE 1.6.7.

When programming you should see the Tx/Rx and yellow LEDs flicker. If not, press Reset when it starts to upload and try again.

Have you followed the instructions here? Arduino Troubleshooting.

  I installed the arduino software using apt-get ...

Personally I download the IDE from this page: https://www.arduino.cc/en/Main/Software

Update

I just compiled and uploaded "Blink" with IDE 1.6.7 to my Micro on Ubuntu 14.04. This is what I saw:

Forcing reset using 1200bps open/close on port /dev/ttyACM1
PORTS {/dev/ttyACM0, /dev/ttyACM1, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, /dev/ttyACM1, } => {/dev/ttyACM1, }
Found upload port: /dev/ttyACM1
/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avrdude -C/home/nick/Development/arduino-1.6.7/hardware/tools/avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -P/dev/ttyACM1 -b57600 -D -Uflash:w:/tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex:i

avrdude: Version 6.0.1, compiled on Apr 14 2015 at 19:04:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/home/nick/Development/arduino-1.6.7/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/nick/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM1
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .
Found programmer: Id = "CATERIN"; type = S
    Software Version = 1.0; No Hardware Version given.
Programmer supports auto addr increment.
Programmer supports buffered memory access with buffersize=128 bytes.

Programmer supports the following devices:
    Device code: 0x44

avrdude: devcode selected: 0x44
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e9587
avrdude: reading input file "/tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex"
avrdude: writing flash (4456 bytes):

Writing | ################################################## | 100% 0.33s

avrdude: 4456 bytes of flash written
avrdude: verifying flash memory against /tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex:
avrdude: load data flash data from input file /tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex:
avrdude: input file /tmp/build8f287ac41038dd4edf2d64ea95be7b6f.tmp/Blink.ino.hex contains 4456 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.03s

avrdude: verifying ...
avrdude: 4456 bytes of flash verified

avrdude done.  Thank you.

Can you please compare to what you get? Or post exactly what you see?

What do you see in your Port menu? This is what I see:

Installing Arduino on a fresh Ubuntu system

I did the following steps to get Arduino up on Ubuntu 14.04, on a PC where it was not previously installed.

Download and install

Downloaded Linux IDE 1.6.7 (64 bit) from https://www.arduino.cc/en/Main/Software
Un-archive downloaded file into ~/development folder
Executed from terminal:  ./arduino

Compile "blink"

Selected Uno device type
Loaded "Blink" from examples
Uploaded (checked Uno showed in menu as shown above)
Got error:

Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied
ioctl("TIOCMGET"): Inappropriate ioctl for device

Check permissions, join dialout and tty groups

See owner of /dev/ttyACM*

$ ls -l /dev/ttyACM*
crw-rw---- 1 root dialout 166, 0 Feb  1 07:32 /dev/ttyACM0

Am I in that group? (No)

getent group dialout
dialout:x:20:

Add to group dialout:

$ sudo usermod -a -G dialout nick

Am I in that group? (Yes)

$ getent group dialout
dialout:x:20:nick

Try again:

avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied
ioctl("TIOCMGET"): Inappropriate ioctl for device
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Add to group tty:

$ sudo usermod -a -G tty nick

Check groups I am in:

$ groups nick
nick : nick adm tty dialout cdrom sudo dip plugdev lpadmin sambashare

Try again (same error).

Log out and log back in

After logging out and back in, it uploaded OK! Changed to Micro board (very similar to Leonardo) - still uploaded OK (after changing board type in IDE).

Check USB for Micro

After reset:

$ lsusb | grep Arduino
Bus 002 Device 014: ID 2341:0036 Arduino SA

After about 3 seconds:

$ lsusb | grep Arduino
Bus 002 Device 015: ID 2341:8037 Arduino SA


pinMode is actually declared as void pinMode(uint8_t, uint8_t);  in arduino.h

A0 is a defined as a number (somewhere depending on the actual hardware), on an Uno/Nano it translates to 14, and when executing pinMode it translates to the appopriate bit in the correct DDRx register.


Replacement for #include  on particle photon

There are some Arduino libraries, that just implements functionalities that do not depend on hardware. Example of these are almost all those libraries that deal with data structures/types (strings, arrays, trees, lists, etc), or particular algorithms.
If such libraries do not depend on other Arduino-specific libraries, you can use them almost certainly.

Other libraries, instead, heavily depend on the hardware currently used on the Arduino boards. In those cases, the library must access the hardware, therefore they will include verious headers, such as pins_arduino.h (in particular, pin_arduino.h .

These won't work without heavy modification of such libraries and/or the creation of a wrapper header to "emulate" the required functionalities and define the required macros/constants, according to your hardware.


How do I turn a number of pins to high and then off after 5 seconds based on a serial command

Have you tried the delay() function? Try putting this in the loop() function for pin 3.

digitalWrite(3, HIGH);
delay(1000); // time in milliseconds as parameter
digitalWrite(3, LOW);


Difference between SoftwareSerial and Serial

All Atmel MCU, on which Arduino models are based, include special hardware for serial communication; this part of the MCU is called USART (stands for Universal Synchronous/Asynchronous Receiver/Transmitter).

Based on the Arduino model you have, you may have only one (eg on UNO) or more USART (leonardo, mega...) on the board MCU.

Each MCU USART is mapped to specific pins of the board, you cannot change those pins.

On Arduino, if you use the monitor to send debug information to your PC, then one USART is used, this is when you used Serial.

If you need more than one serial communication link (e.g. because you have some devices that communicate through serial) but your Arduino model has only one USART, then you have to use the library SoftwareSerial that "simulates" the job of an USART only by software. Hence it is much less optimized than the hardware USART.

One advantage of SoftwareSerial is that you can map it to any pair of pins you like.

Going to your code sample:

if (mySerial.available())
    Serial.write(mySerial.read());
if (Serial.available())
    mySerial.write(Serial.read());

Obviously here, Serial is used for debugging (sending info to the serial monitor of your PC), whereas mySerial is used to communciate with the GSM device.

So this sketch is used to allow you to type AT commands on the monitor, which will then be forwarded to the GSM device; conversely, any strings returned from the GSM device will be echoed to the serial monitor.


// open a new file and immediately close it:

Serial.println("Creating example.txt...");
myFile = SD.open("example.txt", FILE_WRITE);
myFile.close();

This is what you missed (I guess..).
Please see the link and check the steps followed:
https://www.arduino.cc/en/Tutorial/Files


433MHz transmitter and receiver pair doesnt work

These types of receivers are AC coupled so you will not be able to do what you are doing as you need to have regular transitions in the signal and not stay in one state for too long.

They are also limited in the speed at which they will work, I expect 19200 bps is too fast.

You need to use a modulation technique such as Manchester Encoding or other technique that guarantees a suitable density of transitions, can synchronize the data and perform error checking.

One popular software library that does this is VirtualWire Arduino Library that is designed for Arduino and the type of transmitters and receivers you are using.


I've looked at rotary encoders, but even those with no detents have about 24 pulses per rotation.

It sounds like you have been looking at encoders intended for user input controls.

Optical Rotary Encoders for machinery applications are readily available with up to several thousand pulses per revolution.  Prices vary depending on if the wheel is glass or plastic, mounting options, brand, etc.

Do be aware that especially at the high resolutions, getting the encoder disk mounted perfectly concentric to the shaft being measured in important.  You would either need to buy a a wheel which already has a bushing of the same diameter as your shaft, have access to a lathe, or have something custom made.  (This is probably a case where a 3d printer is not accurate enough)

Also keep in mind that encoder wheels are often specified in cycles per revolution; with the typical two channel read head and quadrature decoding, there will be four times as many distinct state transitions.  So a mere 300 CPR wheel would give you 1200 counts per revolution.


How Arduino UNO differentiate between program/flash and serial terminal data

Unlike out kids it does what it is told, not what we thought we told it to do.  Different instructions do different things. Serial.print("Hi"); is stored in RAM will print from Ram, however if you Serial.print(F("Hi"); it will print from flash. The "F" macro tells it where to print from. The Serial.print("Hi"); is stored in flash but moved to RAM and stored there while your program is started and is running whether you print it or not. The "F" macro keeps it in flash not using RAM. Everything that happens when it starts either in your code or the boot loader is code that has been programed and stored in the flash. The Boot loader decodes the code data stream when uploading and stores it in the specified location. It does not know what it is it just reads it and stores it. I do not know what it is called here but there use to be a program module called "CSTART" that upon reset got control; initialized all the memory and set up the variables before turning control over to the user program. Arduino does the same thing, data has to be placed in the right place before starting.


Using Arduino for simultaneous lighting effects

Avoid delay() and use specific times of next actions and compare them to millis().  For a random time, set something like:

now=millis();
...
if(nextFlicker < now) {
   toggleFlicker();
   nextFlicker=now+random(10000);
}
if(nextPulse < now) {
   nextPulse=now+ isPulseOn? 100 : 1000 ;
   togglePulse();
}

...

If you are running more than the 50 day roll-over time of millis(), you may need some care to handle the overflows.  See http://playground.arduino.cc/Code/TimingRollover

For the strobing leds, investigate the timer-controlled outputs outputs.


Problem while interfacing LCD screen with Arduino

In the setup() you have to state what pin the Vo (display contrast pin) on the LCD is connected to. Before the

lcd.begin(16,2)

try

analogWrite(pin Vo is connected to, contrast you want to set the screen to);

An example would be:

analogWrite(6,80);


Does Linux have software protection on USB? Or has the magic smoke escaped?

The fact that you're referencing ttyUSB0 tells me you have cheap Chinese clones and not genuine Ardunios.  These are usually based around the CH340 USB interface chip which is notoriously unreliable.
Your UNO is dead.
My supposition is that plugging it in cripples the CH340 driver.  Any other boards that you subsequently plug in can not be recognised because the driver is in a bad state.
To prove this:

Unplug the UNO
Reboot (power cycle) the computer
Plug in the Nano

It should recognise the Nano fine.

Unplug the Nano
Plug in the UNO

It should fail now.

Unplug the UNO
Plug in the Nano

The Nano should now also fail.
If that sequence is correct then the Uno is definitely dead. Throw it away, or at least never plug it in through USB ever again (you could program over serial through the TX/RX pins or using ICSP as if it were a breadboard Arduino though).


I notice that your code only mentions "child1", but the output you've displayed mentions "child 2". I assume that means you're using more than one instance of SoftwareSerial.

It's important to note that only one instance can receive data at any given time. You need to call listen() on an instance to enable it, which will prevent any other instance from receiving data. (Anything which would have been received by another instance will be discarded.)

See the documentation here: http://www.arduino.cc/en/Reference/SoftwareSerialListen


Use ultoa() instead of dtostrf(). The former is meant to serialize
unsigned long integers, while the later is for floating point numbers.
By using dtostrf(), you are implicitly converting unixt to a
floating point number. The Arduino Mega only supports single precision
floating point, so this conversion incurs some loss of precision, hence
the result you see.