text:
Arduino Due - creating an 8Mhz clock signal
I am attempting to interface a OV7670 camera to an arduino Due. (I am fairly new to this although have been programming for many years).
I need to generate a clock signal for the camera at a minimum of 8Mhz - I realise using the pre-scalers I can only get an approximation but I am cool with that.
I finally got a nice steady 3mhz signal from the sketch below (note that the irq routine for TC6 is not used and will be removed very soon (as soon as I get home).
I think I have a conceptial problem with the timers because as I am initialising RA and RC to 1 and telling via TC_Configure to toggle the line, and because I am using CLOCK1 (42 Mhz), I believe with those values of RA and RC I should be getting a 21'ish MHZ signal.
Ie RA starts at zero. First CLOCK1 tick. (at second/48,000,000) interval. RA Goes to 1 COmpares to RC Because they are equal, resets RA to 0 and toggles TIOA6 Next Clock1 tick occurs.....
As I said I am only getting a 3Mhz signal.
void TC6_Handler()
{
        TC_GetStatus(TC2, 0);

}

void startTimer(Tc *tc, uint32_t channel, IRQn_Type irq) {
        pmc_set_writeprotect(false);
        pmc_enable_periph_clk((uint32_t)irq);

        TC_Configure(tc, channel,
               TC_CMR_WAVE |
               TC_CMR_WAVSEL_UP_RC |
               TC_CMR_TCCLKS_TIMER_CLOCK1|
               TC_CMR_ACPA_TOGGLE );  // RC compare TOGGLES TIOA);

        TC_SetRA(tc, channel, 1); //50% high, 50% low
        TC_SetRC(tc, channel, 1);

        PIO_Configure(PIOC,
                   PIO_PERIPH_B,
                   PIO_PC25B_TIOA6,
                   PIO_DEFAULT);

       TC_Start(tc, channel);

}

void setup(){

        startTimer(TC2, 0, TC6_IRQn);
}

void loop(){
}

FWIW, I checked the ATMEL timer doc (again) and confirmed for a 8mhz'ish signal, RC should be set to 5.xxx (call it six) and RA should be set to 3 (50% duty cycle). Needless to say, this did not give me a 8Mhz signal. In that there is a very faint possibility that I have damaged the ARM (accidently put 5v on it a while back and Wire is a bit falky (but wire1 is good), is there any chance anyone with a Due and a logic analyser could run the sketch and tell me what signal you are getting on TIOA6?

the code below should give you a 8.4MHz signal on digital pin 7 of the due. I have used it to generate a 4.2MHz clock (by setting REG_PWM_CPRD6 = 20; and REG_PWM_CDTY6 = 10; but I think it should work for a 8.4MHz clock also.
I have been using this to provide a 4.2MHz clock signal instead of using a crystal oscillator for an ADE7913 and can confirm it is working well in that application. I have taken this from the arduino forum here.
#include <Arduino.h>

const unsigned long serialPeriodMillis = 2000;
unsigned long previousMillis = 0;

void setup()
{
  int32_t mask_PWM_pin = digitalPinToBitMask(7);
  REG_PMC_PCER1 = 1 << 4;                         // activate clock for PWM controller
  REG_PIOC_PDR |= mask_PWM_pin;                   // activate peripheral functions for pin (disables all PIO functionality)
  REG_PIOC_ABSR |= mask_PWM_pin;                  // choose peripheral option B
  REG_PWM_CLK = 0;                                // choose clock rate, 0 -> full MCLK as reference 84MHz
  REG_PWM_CMR6 = 0 << 9;                          // select clock and polarity for PWM channel (pin7) -> (CPOL = 0)
  REG_PWM_CPRD6 = 10;                             // initialize PWM period -> T = value/84MHz (value: up to 16bit), value=10 -> 8.4MHz
  REG_PWM_CDTY6 = 5;                              // initialize duty cycle, REG_PWM_CPRD6 / value = duty cycle, for 10/5 = 50%
  REG_PWM_ENA = 1 << 6;                           // enable PWM on PWM channel (pin 7 = PWML6)

  Serial.begin(115200);
  Serial.println("Serial on");
}

void loop()
{
  if (millis() - previousMillis > serialPeriodMillis) {
    Serial.println("TIC");
    previousMillis = millis();
  }
}

p.s. obviously you don't need the serial stuff, I've just put that in there to check that the code isn't hanging.

Example from Khalid Abdulla is correct, but I used 10.5 MHz for my ov7670 camera:
int32_t mask_PWM_pin = digitalPinToBitMask(7);
REG_PMC_PCER1 = 1<<4;               // activate clock for PWM controller
REG_PIOC_PDR |= mask_PWM_pin;  // activate peripheral functions for pin (disables all PIO functionality)
REG_PIOC_ABSR |= mask_PWM_pin; // choose peripheral option B
REG_PWM_CLK = 0;                     // choose clock rate, 0 -> full MCLK as reference 84MHz
REG_PWM_CMR6 = 0<<9;             // select clock and polarity for PWM channel (pin7) -> (CPOL = 0)
REG_PWM_CPRD6 = 8;                // initialize PWM period -> T = value/84MHz (value: up to 16bit), value=8 -> 10.5MHz
REG_PWM_CDTY6 = 4;                // initialize duty cycle, REG_PWM_CPRD6 / value = duty cycle, for 8/4 = 50%
REG_PWM_ENA = 1<<6;               // enable PWM on PWM channel (pin 7 = PWML6)

My results: Arduino Due and OV7670

1) Timer counts close to zero are useless... i.e. they work same, as if count = 0; (I ran Due timers with TIMER_CLOCK_2 i.e. MCK/8 or 10.5MHz many times)
2) Select a reasonable pre-scalar depending on output frequency you need such that RC count will be a bit more. Here 42 MHz (TIMER_CLOCK_1)  means you need a count of RC = 5 approximately (with RA = RC/2 for 50% duty ratio) for 8 MHz. When RA closes to RC we get output of half frequency i.e. close to 4 MHz.
I think here better option is to use master clock itself i.e. 84 MHz, then RC = 10 (approximately)(with RA = RC/2 for 50% duty ratio). Master clock can be selected using TIMER_CLOCK_5 (I am not sure..please check in the data sheet).
May be Arduino Due (with its clock and using timers) is not good option to generate pulses at that higher frequency (you can't execute other routines in just 10 clock cycles!) . If no additional processing is needed, why not go for a pulse generating IC....just my opinion :-)

Thanks for that - am checking (It seems timer5 is not the system clock). Using 3/6 on Timer 2 gives me a mixed wave of up to 6Mhz. (Also using UPDOWN_RC. 2/4 gives me a sloppy wave consisting of a 2Mhz, a bit of 6 and a bit of 4. Seems however you are right that low numbers give very inconsistent results. I agree that an external clock may be the way to go - but I am not beaten yet :-) Many thanks for responding. Stan

Thanks to all who responded and advised. Have ordered external clock generator (Adafruit). (Have also confirmed with the answers etc that I am not going nuts..... Stan


text:
Why is my real time clock getting the wrong time from my PC?
I want my real-time clock to set its time as the time on my PC. However, when I run the following sketch, the real-time clock reports the time as being 32-33 seconds earlier than my PC says the time is.
#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 RTC;

void setup () {
  Serial.begin(57600);
  Wire.begin();
  RTC.begin();

  if (! RTC.isrunning()) {
    Serial.println("RTC is NOT running!");
// following line sets the RTC to the date & time this sketch was compiled
// uncomment it & upload to set the time, date and start run the RTC!
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }
}

void loop () {
  DateTime now = RTC.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();
}

I have also tried manually setting the time on the RTC, but I end up with the same problem: the RTC is always 32-33 seconds behind what I set it to. The lag happens as soon as I run the sketch. It seems very odd to me that no matter how I try to set the time, I end up with exactly the same error. I can tell the Arduino to report the time as being 33 seconds after what the RTC says it is, but this solution seems kind of sketchy, and I am worried that something is fundamentally wrong with my RTC or the way I am using it.
I am using an Arduino Uno with an Assembled Data Logging Shield from Adafruit. The data logging shield uses a DS1307 RTC. Has anyone had this problem before, or have any ideas about what could be causing it? Any help would be much appreciated.

Ive taken Hugo Bertini and Oli explanation to use in my projects and it works ! Thank you (: but it goes faster by 26 seconds....

The __DATE__ and __TIME__ are set when the code is compiling so they will naturally be behind since the code still needs to finish compiling and then be flashed to the chip.
See the Arduino Playground for an example of how to sync it to your computer over serial.

TimeSerial.pde shows Arduino as a clock without external hardware.
It is synchronized by time messages sent over the serial port.   A
  companion Processing sketch will automatically provide these messages
  if it is running and connected to the Arduino serial port.

I am experiencing a similar problem with an Arduino UNO and a Nano. Both from the same PC.
 Indeed it looks like the time it takes from compile time to upload + MCU start is reflected.
Assuming the RTC has a good battery and the compilation + upload times are consistent, then adding a drift compensation to the code seems to do the trick.
Here's how I did it (in my case 7 seconds did the "trick" - sorry for the hardocode, but that's for mere description purposes):
RTC.adjust(DateTime(__DATE__, __TIME__));
DateTime t = DateTime(RTC.now().unixtime()+7);
RTC.adjust(t);

Regards,
Hugo Bertini

With the <DS1307RTC.h> library the DS1307 can be adjusted during time setup, by using a global variable and then adding this to Sec reading in the getTime() function, for example as follows:
#include <DS1307RTC.h>
tmElements_t tm;
byte adjustt = 8;  // adustment for seconds lag allowing for compiler download time

/*********************

bool getTime(const char *str) {
  int Hour, Min, Sec;
  if (sscanf(str, "%d:%d:%d", &Hour, &Min, &Sec) != 3) return false;
  tm.Hour = Hour;
  tm.Minute = Min;
  tm.Second = Sec + adjustt;
  return true;
}

You can fix the offset by calling once the following code in the setup() function:
RTC_DS3231 rtc;

DateTime now = rtc.now();
rtc.adjust(DateTime(now.unixtime() + 10)); // add 10s to current time for fixing the offset

The Arduino takes the computer time and sends it to the DS1307. The time it takes to copy is the one you are seeing wrong. I would solve the problem by advancing the computer time the necessary seconds that you say is delayed and when programming you should have the exact time.

source: Stack Exchange

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

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

sort: votes


text:
Controlling a capacitive touch screen that doesn't have I2C/SPI
I have been searching for cheap slim 3" 16:9 capacitive touch screens for a while now. But I couldn't find any that had an I2C or SPI interface. The cheap displays always have these ribbon cables with a ton or pins and it's really hard to find a way to control them from an Arduino (or ESP-32 or ESP-8266).
I recently found this one, but how do you access such a touch screen that doesn't have an I2C or SPI interface?
Do I need some sort of driver board? What exactly would I be look for?

... You would look for the HX8352B datasheet and start reading.

I've never seen a I2C interface board for a proper display (the LCD 16x2 piggyback boards excluded).  Could you use something like this as a starting point MTCH6303-I/PT

@Matt I'd agree it isn't really an Arduino topic, but the touch issue is hardly an ESP8266 topic either - as Majenko points out it needs a capacitive touch controller.  If the touch issue were solved, the greater bandwidth and memory the ESP devices may make driving the display itself a bit easier than with an Arduino, but that's not the question being asked.

Do I need some sort of driver board?

There are quite a few solutions around to interface with parallel devices like that. Some can be purchased off-the-shelf. I described a home-made solution on my page Connecting a graphical LCD via a I2C/SPI using a 16-bit port expander.
This isn't a touch screen, but from what I can make out of your (rather hard to read) image, it looks similar in concept.

I used a MCP23017 16-bit port expander (that is an I2C part, but you can get the MCP23S17 chips which has an SPI interface).
As you can see from the photo, there are only four wires from the Arduino to the LCD board: +5V, Gnd, SDA, SCL.
When I wrote that article it looks like the MCP23017 was $AUD 2.30. A quick Google search indicates it is still selling for around $US 2.50. On eBay they seem to be selling for around one dollar (eg. $5 for 5 chips).
Depending on the complexity of the driver (on the touch-screen board) writing suitable code may be moderately easy to slightly harder. It depends on how much you are used to coding for these port expanders, and how fiddly the interface requirements are.
Since Adafruit offer a driver shield, it can presumably be done.

There are two major parts to a capacitive touchscreen:

The touch panel
The controller chip

You have to have both in order to use the panel.
Basically the panel is like a matrix of capacitive sensors, and the controller chip has to rapidly cycle through each row of them (or column if you hold it the other way) sensing all the inputs on that row. It's quite a complex task, and so a special chip is really required for the job.
It's that chip, not the touch screen panel, that presents the SPI or I2C interface.

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


text:
How to control an Arduino connected device accross the Internet?
Actually i am trying to do IoT based work.
Until now the sensed data(temperature and humidity) has been made available to only for one user on the Internet using Apache tomcat. So far we have just created a one way communication link between the sensor node and the Internet through the PC.
Now I need to control a device (say a fan) according to the variation with sensed temperature from anywhere through the internet. For the HTML I have used Java Script, which I am new to.

I'm voting to close this question as off-topic because you are asking a Java related question. At leat you should add an example about what you have tried to far.

Possible duplicate of Arduino Control over the internet

@Mattia JavaScript is not Java...

Perhaps a message brokering service like MQTT is what you are looking for. Far too much to it to explain it all here, but basically it lets you publish messages and subscribe for messages, over a network.

If you are planning on keeping the Arduino connected to the PC then you are looking for help with your javascript, which isn't a question for this forum.
If you are looking at making the Arduino independent from the PC then you want to look at possible network options for the Arduino, ESP8266 shield, Mobile phone, C5100 (?).
Of course you might also want to look at using an ESP8266 rather than an Arduino and programming that through ArduinoIDE and using its web server rather than Apache.  There are samples that would show you how to do this, you could get them without getting the hardware, but obviously they won't run.

How about this:
http://www.instructables.com/id/How-to-communicate-with-Arduino-using-HTML-Chrome/
But i also would prefer MQTT, but this requires Network connection for Arduino

For the HTML i have used JAVA SCRIPT(but i am new to java)

You have to keep in mind Java is not the same as javascript.
I've once used my Raspberry Pi to communicate with my Arduino Uno. There is a library available to use on your RPi called PySerial, you can use Python on your Raspberry to listen to your Arduino output and store your values to a database for example. You can also use some Python scripts to send things over your serial connection to your Arduino, for example for your fan to start. You can build a web interface to read or view your data and to control your fan with Java or Javascript.
It may not be the most useful way to do it because you can use a Raspberry Pi as your main device but I've done it before and it is nice for learning purposes.
Good Luck!


text:
Trying to make arduino heart beat counter but couldn't understand code
I am trying to make an Arduino heart beat counter . I looked for some code online and found this code on arduino.cc forum but I couldn't understand working of the given code .. specifically these few lines of code:
The full code is given below:
int sensorValue = 0;
int sensorValue = 0;  // variable to store the value coming from the sensor
int count = 0;
unsigned long time1 = 0;  // store the initial time
unsigned long time2;    // store the current time
void setup() {
    // declare the ledPin as an OUTPUT:
    pinMode(sensorPin, INPUT);
    Serial.begin(9600);
}

void loop() {
    // read the value from the sensor:
    if (count == 0)
    {
        time1 = millis();
    }
    time2 = millis();
    sensorValue = analogRead(sensorPin);
    if (sensorValue > 156)
    {
        increment();
    }
    if (time2 >= time1 + 10000)
    {
        counter();
    }

}

void increment()
{
    count++;
    while (sensorValue > 156)
    {
        Serial.print("Sensor value is greater than .75V\n");
    }
}
void counter()
{
    count = count * 6;
    Serial.print("Heart beat is ");
    Serial.print(count);
    Serial.print(" per min\n");
    time1 = 0;
    time2 = 0;
    count = 0;
}

Lines of code I'm not able to understand :
if (count == 0)
{
    time1 = millis();
}
time2 = millis();
sensorValue = analogRead(sensorPin);
if (sensorValue > 156)
{
    increment();
}
if (time2 >= time1 + 10000)
{
    counter();
}

PS: the given code is in void loop(). in the beginning of the loop.
if u are not able to understand the code i'm leaving a link to the page:this is the link
i would be highly obliged if anyone could really help me soon. Thank u in advance :-)

Just copy paste the code. Don't post screenshot of it.

What exactly don't you udnerstand in this code. Note that this code is using functions (increment(), counter()) that you did not post, hence it will be difficult to answer. As already commented, don't post pictures of code as this would make it more difficult to copy paste into an answer. Finally, provide the exact link where you found this source code.

jfpoilpret i made some revisions in the code now can you help me

I've reformatted you code to make it easier to read.
Looking just at the lines you don't understand.
Line 1 stores the start time of this loop in the variable time1 and stores the current time in the variable time2  these are going to be almost identical until the first heart beat is seen (which will increment count).
Line 6 sensorValue = analogRead(sensorPin); reads the value from the sensor, it the reading is greater than some predetermined threshold (156) then it increment() the counter and waits until the value goes below 156.
Line 11 checks to see if 10 seconds (10,000 mS) have elapsed since the loop started.  If they have then you get your reading via the function counter()
Does that make sense?
It would be a lot easier to understand if the original author had put comments in, but most people writing examples assume there code is so easy to understand they don't need to, don't fall into that trap when you become a great programmer! :)


text:
Switch statements with Bluetooth serial input not working
I am trying to control the brightness of an LED using PWM. I am also trying to make it so that when I click a button on my bluetooth app, I can get it to change the frequency of the PWM pin.
For changing the frequency, I am changing the value of the timers. When I click "30 HZ" on my bluetooth app, I am sending a value of "A", 122 HZ = "B" etc..
I hooked up a oscilloscope and changing the frequency does work.
The problem is that when I click a button, it receives A or B etc.. but it doesn't enter the switch statement every time. It is very laggy. It will also receive inaccurate numbers at times.
I think I need something in differentiating between various serial inputs? (one for choosing frequency and one for the duty cycle of the LEDs)? and also being able to enter the switch statements and then staying in there until another char is received.
Below is my code and I would appreciate any help!
const int pwmPin = 11;
const int TurnLightPin = 13;

int ledState = LOW; // ledState used to set the LED
unsigned long previousMillis = 0;  // will store last time LED was updated
const long interval = 500;  // interval at which to blink (milliseconds)
int dutyCycle = 0;

char state =' ';

void setup() {
  // put your setup code here, to run once:
  //Change register values to adjust PWM frequency for PWM Pins 3 and 11:

  //TCCR2B = TCCR2B & B11111000 | B00000100;    // set timer 2 divisor to           64 for PWM frequency of   490.20 Hz (The DEFAULT)
  //TCCR2B = TCCR2B & B11111000 | B00000101;    // set timer 2 divisor to      128 for PWM frequency of   245.10 Hz
  //TCCR2B = TCCR2B & B11111000 | B00000110;    // set timer 2 divisor to   256 for PWM frequency of   122.55 Hz
  //TCCR2B = TCCR2B & B11111000 | B00000111;    // set timer 2 divisor to  1024 for PWM frequency of    30.64 Hz  pinMode(TurnLightPin, OUTPUT);

  pinMode(TurnLightPin, OUTPUT);
  pinMode(pwmPin, OUTPUT);

  Serial.begin(9600); // Default baudrate of bluetooth -- 9600 bits/second
  Serial.println("HC-06 Bluetooth connected!!!");
  Serial.flush();

}

void loop() {

  // check to see if it's time to blink the LED; that is, if the
  // difference between the current time and last time you blinked
  // the LED is bigger than the interval at which you want to
  // blink the LED.
  unsigned long currentMillis = millis();

   if (currentMillis - previousMillis >= interval) {
     // save the last time you blinked the LED
     previousMillis = currentMillis;

     // if the LED is off turn it on and vice-versa:
     if (ledState == LOW) {
       ledState = HIGH;
     } else {
       ledState = LOW;
   }

   // set the LED with the ledState of the variable:
  digitalWrite(TurnLightPin, ledState);
}

 //PWM Stuff:

while(Serial.available()){

   // if (Serial.available() > 0){
  state = Serial.read();
  Serial.print("State received - Before Switch Statement: ");
  Serial.println(state);
  //}

switch (state) {

case 'A':

  TCCR2B = TCCR2B & B11111000 | B00000111;    // set timer 2 divisor to  1024 for PWM frequency of    30.64 Hz

  while(Serial.available() && (Serial.read() != 'B' || Serial.read() != 'C' || Serial.read() != 'D')){

    dutyCycle = Serial.parseInt();
    int pwmValue = (dutyCycle * 2.55 ); // Multiplied by 2.55 b/c sending a  value between 0-100 and max PWM value is 255
  //AnalogWrite takes two arguments: (pin to write to, and value b/w 0-255)
    analogWrite(pwmPin, pwmValue); //Sets the pin to the value received
    Serial.print("A-30 HZ - PWMValue:");
    Serial.println(pwmValue);
    Serial.print("A-30 HZ - State:");
    Serial.println(state);
    }

    state = ' ';
    break;

case 'B':
    TCCR2B = TCCR2B & B11111000 | B00000110;    // set timer 2 divisor to   256 for PWM frequency of   122.55 Hz

    while(Serial.available() && (Serial.read() != 'A' || Serial.read() != 'C' || Serial.read() != 'D')){

    dutyCycle = Serial.parseInt();
    int pwmValue = (dutyCycle * 2.55 ); // Multiplied by 2.55 b/c sending a value between 0-100 and max PWM value is 255
  //AnalogWrite takes two arguments: (pin to write to, and value b/w 0-255)
    analogWrite(pwmPin, pwmValue); //Sets the pin to the value received
    Serial.print("B-122 HZ - PWMValue:");
    Serial.println(pwmValue);
    Serial.print("B-122 HZ - State:");
    Serial.println(state);
  }

  state = ' ';

  break;

case 'C':

   TCCR2B = TCCR2B & B11111000 | B00000101;    // set timer 2 divisor to   128 for PWM frequency of   245.10 Hz

    while(Serial.available() && (Serial.read() != 'A' || Serial.read() != 'B' || Serial.read() != 'D')){

    dutyCycle = Serial.parseInt();
    int pwmValue = (dutyCycle * 2.55 ); // Multiplied by 2.55 b/c sending a value between 0-100 and max PWM value is 255
   //AnalogWrite takes two arguments: (pin to write to, and value b/w 0-255)
    analogWrite(pwmPin, pwmValue); //Sets the pin to the value received
    Serial.print("C-245 HZ - PWMValue:");
    Serial.println(pwmValue);
    Serial.print("C-245 HZ - State:");
    Serial.println(state);
  }

  state = ' ';

  break;

case 'D':

    TCCR2B = TCCR2B & B11111000 | B00000100;    // set timer 2 divisor to    64 for PWM frequency of   490.20 Hz (The DEFAULT)

    while(Serial.available() && (Serial.read() != 'A' || Serial.read() != 'B' || Serial.read() != 'C')){

      dutyCycle = Serial.parseInt();
      int pwmValue = (dutyCycle * 2.55 ); // Multiplied by 2.55 b/c sending a value between 0-100 and max PWM value is 255
    //AnalogWrite takes two arguments: (pin to write to, and value b/w 0-255)
      analogWrite(pwmPin, pwmValue); //Sets the pin to the value received
      Serial.print("D-490 HZ - PWMValue:");
      Serial.println(pwmValue);
      Serial.print("D-490 HZ - State:");
      Serial.println(state);
    }

    state = ' ';

    break;
default:

  TCCR2B = TCCR2B & B11111000 | B00000110;    // set timer 2 divisor to   256 for PWM frequency of   122.55 Hz

  while(Serial.available()){

    dutyCycle = Serial.parseInt();
    int pwmValue = (dutyCycle * 2.55 ); // Multiplied by 2.55 b/c sending a  value between 0-100 and max PWM value is 255
    //AnalogWrite takes two arguments: (pin to write to, and value b/w 0-255)
    analogWrite(pwmPin, pwmValue); //Sets the pin to the value received
    Serial.print("default - PWMValue:");
    Serial.println(pwmValue);
    Serial.print("Default - State:");
    Serial.println(state);
  }

  state = ' ';

  break;
    }//End of Switch Statement
  } // End of While loop for PWM
} // End of void Loop

I don't like your serial parser at all. Lots of whiles, reads, places to get stuck in...
For example mine looks like:
void loop() {

  if (Serial.available()) {
    int ch = Serial.peek(); // check first character in buffer

    switch (ch) {
      case 'a' ... 'd':
        TCCR2B &= 0b11111000; // mask out prescaler (turn off timer 2)
        TCCR2B |= 0b111 - (ch - 'a'); // a => 7, b => 6, c => 5, d => 4
        Serial.read(); // remove character from buffer
        Serial.println(TCCR2B, HEX);
        break;

      case 'A' ... 'D':
        TCCR2B &= 0b11111000; // mask out prescaler (turn off timer 2)
        TCCR2B |= 0b111 - (ch - 'A'); // A => 7, B => 6, C => 5, D => 4
        Serial.read(); // remove character from buffer
        Serial.println(TCCR2B, HEX);
        break;

      case '0' ... '9':
        dutyCycle = Serial.parseInt();
        analogWrite(pwmPin, (int)(dutyCycle*2.55));
        Serial.println(dutyCycle);
        break;

      default:
        Serial.read(); // some invalid character? Drop it
        break;
    }
  }
}

However it needs some extra character after number (needed by parseInt)

i had major issues with ws2812 and the hm-10, and i couldn't get a great solution for it, and although your setup is different, it may help…
my solution was to stop things that were interrupting the interrupt, in this case, the leds, so to create;
void dataLow () {
  // drop the power on the data pins for the leds
  digitalWrite(DATA_PINA, LOW);
  digitalWrite(DATA_PINB, LOW);
  Serial.println("DATA_PINS - LOW");
}

void dataHigh () {
  // turn the power back on for the leds
  digitalWrite(DATA_PINA, HIGH);
  digitalWrite(DATA_PINB, HIGH);
  Serial.println("DATA_PINS - HIGH");
}

and then to clean the data. i was looking for 2 numerical characters, and if i got anything else, then dump the data.
bluetooth.listen();
while (bluetooth.available() > 0) {
    dataLow();
    char inChar = bluetooth.read();
      // if its a character, add it to the string
      if (isDigit(inChar)) {
        inString += (char)inChar;
      }
      // if the string is longer than 2, truncate and return nothing
      if(inString.length() > 2) {
        inString[2] = '\0';
      }
      // if the serial recieves bluetooth end of line /n print string data out
      if (inChar == '\n') {
        Serial.print("String: "); Serial.println(inString.toInt());
        program=inString.toInt();
        inString = "";
        dataHigh();
      }
      // read user input from serial monitor
      if (Serial.available()){
        delay(10); // The DELAY!
        bluetooth.write(Serial.read());
      }
  }

it was still twitchy, but it mostly works.


text:
Problem with code for IR remote controlled robot
I recently wrote the code for this project but it's weird because when I press button on the remote nothing shows up on the Serial Monitor and consequently the robot doesn't respond. I know it's not a hardware issue because when I used the IRrecv Demo sketch values were displayed on the serial monitor
Please tell me what's wrong! I'm sure there are a lot of talented programmers out there!!
#include <IRremote.h>
#include <AFMotor.h>
AF_DCMotor rightMotor(1); // Right motor connected to port 1
AF_DCMotor leftMotor(2); // Left motor connected to port 2
IRrecv irrecv(A2);// IR receiver connected to pin A2(ANALOG PINS ON MOTOR             SHIELD USED AS DIGITAL INS!)
decode_results results;
#define Straight 0xC1CC42BD
#define Right 0xC1CCA25D
#define Left 0xC1CC22DD
#define Back 0xC1CCC23D

void setup(){
  Serial.begin(9600); // Establishing Serial Communication, THIS IS     IMPORTANT!!
  irrecv.enableIRIn(); // Start the receiver
}
void loop() {
  if (irrecv.decode(&results))
  {
      Serial.println(results.value, HEX);

      if((results.value)== Straight)
      {
      moveForward();
      }
      if((results.value)== Right)
      {
        turnRight();
       }
      if((results.value)== Left)
      {
        turnLeft();
      }
      if((results.value)== Back)
      {
        moveBackward();
      }
      else
      {
        Stop();
      }
      irrecv.resume();
  }
  delay(100);
}

void moveForward() {

    leftMotor.setSpeed(255);
    rightMotor.setSpeed(255);
    leftMotor.run(FORWARD);
    rightMotor.run(FORWARD);
}

void turnRight(){

  leftMotor.setSpeed(200);
  rightMotor.setSpeed(200);
  leftMotor.run(FORWARD);
  rightMotor.run(BACKWARD);
  delay(400);

  leftMotor.run(FORWARD);
  rightMotor.run(FORWARD);
}

void turnLeft() {

  leftMotor.setSpeed(200);
  rightMotor.setSpeed(200);
  leftMotor.run(BACKWARD);
  rightMotor.run(FORWARD);
  delay(400);

  leftMotor.run(FORWARD);
  rightMotor.run(FORWARD);
}
void moveBackward() {

    leftMotor.setSpeed(200);
    rightMotor.setSpeed(200);
    leftMotor.run(BACKWARD);
    rightMotor.run(BACKWARD);
}

void Stop(){
    leftMotor.setSpeed(0);
    rightMotor.setSpeed(0);

}

You are using two libraries (Arduino-IRremote & Adafruit-Motor-Shield-library) which both use Timer2 on the microcontroller.
The motor library actually changes the setup of timer 2 (see line 92 of AFMotor.cpp) which will disrupt the timing that the IR sensor uses to determine the IR code received.
As far as I can see, the IR library is using Timer2 only. This means you should be able to change your motors over to port 3 & 4 which use Timer0 instead.
AF_DCMotor rightMotor(3); // Right motor connected to port 3
AF_DCMotor leftMotor(4); // Left motor connected to port 4

Try replacing you loop function with this one.  It won't fix it.
void loop()
{
    if (irrecv.decode(&results))
    {
        Serial.println(results.value, HEX);

        switch (results.value)
        {
        case Straight:
            moveForward();
            break;
        case Right:
            turnRight();
            break;
        case Left:
            turnLeft();
            break;
        case Back:
            moveBackward();
            break;
        default:
            Stop();
        }
        irrecv.resume();
    }
    else
    {
        Serial.println ("Nothing received");    // This message will annoy you so comment it out as soon as you are happy with what is happening.
    delay(100);
}

The switch statement is just a neater way of doing your ifs.  The Nothing received message will show you if decode is ever returning.  If it is returning you need to work out why it is returning false, by looking in the library code.  If it isn't returning then you need to look in the library code and see why.  If it is returning, but not giving you an expected value, you need to look in the library code and see why.
Sorry but from what you describe it seems to be an issue with the library or your use of it, could be anything, but when you can get some more info post it back here.


text:
How can I have two Arduino Uno's communicate wirelessly?
I'm an art student, using arduino in an Electronic Arts Class.  I have already created a skateboard speedometer, using a Hall Effect Sensor and a magnet embedded in one of my skateboards wheels.  I've attached a speaker to the arduino that plays a tone, with the pitch depending on the RPM's of the wheel.  (the faster the board is going, the higher pitch the tone being played is).  Currently the speaker is attached to the skateboard and wired directly to the arduino.  My goal is to have a speaker with an arduino wirelessly connected to the arduino on the skateboard.  The arduino on the skateboard record's the RPM's and then wirelessly send that information to the second arduino to play the tone through the speaker.  Is this possible? what hardware would yo recommend? I've been looking at the Bluetooth HC-05 but I'm not sure this will work.  Thanks for any help!

The nRF24L01+ modules are a popular choice for this type of thing, and will be much more direct to work with than anything Bluetooth.  You could also consider using a short range analog radio to send audio generated at the source with a stock headphone/speaker audio receiver, but may have trouble finding a quiet channel in an urban area.

@ChrisStratton So two of the nRF24L01+ modules connected to both arduino's should do the trick?

Probably, at least if misoperation/non-operation has no serious consequences.  For a point of comparison, a significant minority of the little quadcopter toys fly around via signals sent through compatible transceivers.

If you do buy the modules, make sure you download the library either through the IDE or from github.com/TMRh20/RF24. That way you'll have a library that has active development and is almost bug free.

ESP8266 is also a good choice. these little guys are really useful and give you a Wi-Fi connection between your Arduino boards.
Also, the cost of one ESP8266 is about $3.. super cheap!


text:
How to use power led from arduino-pro-micro?
In my project I need 3 leds. I would like to use on-board leds if possible.
I know how to use PB0 and PD5 red on-board leds, and I would like to hack the board somehow to use the green power led.
If I do not find a way to use the power led from MCU, I'm planning to destroy it anyway, because it is constantly on, which is harmful in my project.

refer to the schematic

The power led is connected directly to the 5V line. So you'd need to modify the board (cut a trace and add a tiny wire).

There are 34-pin atmega32u4-based boards. They have 3 leds. So use them instead of pro-micro board.

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


text:
Interfacing Arduino UNO with TFT LCD and WiFi Shield
I'm trying to interface my Arduino UNO with both a 1) TFT LCD screen and 2) WiFi Breakout board/shield.
The WiFi breakout board uses many of the same Digital pins as the LCD screen so is it possible for the arduino to interface with both devices simultaneously?
I also noticed that the shield goes over the arduino, but covers the header pins. Does this mean that I can't use these pins?
I've never worked with shields or breakout boards and would like some advice before I purchase either component.
If neither of these solutions will work, please provide me with alternate methods.
Your time/feedback is greatly appreciated :)
-Vip

This isn't a very well matched selection of parts - even if you get the wiring to work (there are probably ways) both an LCD display and wifi tend to need a fair amount of RAM to use effectively, and your Uno has a mere 2048 bytes which will require very careful budgeting.  You would do much better with a processor having both more memory as well as more pins.

I agree with Chris on this. The uno is limited where it comes to pins and and ram, you should probably look at a mega, or similar.
As far as running both at once, i don't think it would be possible with the uno, with the ram limitations, as well as pin limitations, you'll be hard pressed to get them going at the same time, within the same sketch.
While technically it is possible to use alternative pins, i doubt there will be enough unused pins to shift an entire shield over to on the Uno
If you're looking for a cheaper rout, you may look at adding a secondary Uno to run the wifi, and send any data you need displayed to the uno running the tft via serial coms.

Thank you both for the great feedback. @ArcAIN6 Is there a link to a tutorial where I can interface two Uno's like you mentioned?
Thanks again.


text:
How to connect to LCD and communicate via serial usb simultaneously? (UNO)
Pretty simple home automation project I am working on. I'm trying to hook my arduino which has a 16x2 LCD, DHT22 temp/humidity sensor to my Pi via usb. I want to be able to maintain the values on the LCD and send the values to the Pi via serial usb.
I am in Arduino IDE currently and can see the serial values in the monitor...however the LCD is all scrambled. Can someone take a look at my code and tell me what I am doing wrong?
#include <LiquidCrystal.h>
#include "DHT.h"

#define DHTPIN 8
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal lcd(1, 2, 4, 5, 6, 7);

void setup() {

  lcd.begin(16, 2);
  dht.begin();
  Serial.begin(9600);
}

void loop() {
  delay(2000);
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  float f = dht.readTemperature(true);

  if (isnan(h) || isnan(t) || isnan(f)) {
    lcd.print("Failed to read from DHT sensor!");
    return;
  }

  lcd.setCursor(0,0);
  lcd.print("Temp = ");
  lcd.print(f);
  lcd.setCursor(0,1);
  lcd.print("Humidity = ");
  lcd.print(h);
  lcd.clear();

  Serial.println(f);
  Serial.println(h);
}

First try a (demo) sketch only for the LCD to see if it works without your own code and the added additional components.

pin 1 is TX of Serial, you can't use it for lcd

So I just need to change the pin 1 out?


text:
How does an LED in an LED-strip like WS2811 know when it should be on or off
I was experimenting with an Arduino board and an LEDstrip WS2811
it works all perfect, but I do not understand how a particular led knows when it is called or adressed. Does every led have a unique address?

You might find the explanations at https://www.edn.com/design/led/4438797/Tips-and-tricks-for-driving-WS2811-LED-strips---Part-1 , https://forum.arduino.cc/index.php?topic=365474.0 and the datasheet https://cdn-shop.adafruit.com/datasheets/WS2811.pdf useful.

after a reset, the WS2811 saves the first colour value it receives and passes the rest of colour values to its output   ..... imagine a line of people and a deck of coloured cards ... the people are instructed when you hear the bell (that is the reset), keep the first card you receive and pass any other card to the next person ... use you imagination to fill in the rest

The WS2811 is the driver chip, that is embedded into the strip. In principle it is some kind of shift register, that outputs PWM values, and on the strip they are daisy-chained (data output of one is connected to data input of the next). With the Arduino you shift out a stream of bytes, when using a RGB strip 3 bytes per LED (1 byte per color). The first WS2811 reads these 3 bytes, sets it's outputs (PWM) according to them and outputs the rest of the datastream to another pin, so that it can reach the next WS2811. The LEDs on the strip are connected to the WS2811's outputs.
So all in all the WS2811 chip saves the current desired state of it's LED, which it got through the data stream from the Arduino. The chips don't have a direct address, but can be identified by their position in the strip. So you cannot only write to the 5th LED without also writing values to the LEDs before it. But, if you don't want to set the whole strip, you can output less data, than the strip as LEDs, effectively ignoring the LEDs at the end.

EDIT:

but How does it recognize the first led?

The strip has somewhat like a data line. When you look at the markings for this line on both ends of the strip, you normally should see something like "DI" and "DO", which means Data In and Data Out, each at one end of the strip. Each LED has it's own Data In and Data Out, which are chained to the next and the previous LED. The first and last LED expose their Data In or Data Out (respectively) to the outside of the strip. You feed the data into Data In of the first LED driver, which outputs the rest of the data at it's Data Out pin, where the data can go to the next driver. So the direction, in which the data flows through the strip is already defined and hardwired. You cannot send data in the other direction through the strip. So the first LED is that one, that is directly attached to the Data In line of the strip and will be connected to the Arduino.
Keep in mind, that this is not an address. You can cut the strip at an appropriate place (so that you don't destroy the circuit. Most strips have these pieces regularly after every or every third LED) and get a new first LED, if you now connect the Data In, where you cut the strip, to the Arduino. An LED strip with WS2811's is not an array or a matrix of LEDs, it is a chain of LEDs. This difference is important in how you control them.

Clear answer, but How does it recognize the first led?

@AnneMabellon  I added extra explanations for this. I hope it is clear now.

The LED units don't have any unique addresses of their own, instead they are indexed by their position in the string of LEDs. When you feed data into the first LED, you put the entire sequence of color values into the first one. It will then set its own color to the first one in the sequence, and then output all the rest to the next LED in the series.
None of the LEDs actually "know" where in the strip they are located, they only take the first value that comes in and set their own color to that value, and then output the rest of the values to the next LED in the series.


text:
How to pass a static const (progmem) array to a function
I'm implementing a voice synthesizer chip. To build a phrase, I create a list of phonemes like this:
static const uint8_t PROGMEM heybuddy[] = {
  pPA5, pHH1, pEY, pPA5,
  pBB2, pAX, pDD2, pIY, pPA5,pPA5,pPA5,
};

And to play them I do this:
 for (size_t i=0; i<sizeof(heybuddy); i++){
    say(pgm_read_byte(heybuddy+i));
 }

So what I'd like to do is create a function where I can just pass the array to a function that can take care of the loop and do some other maintenance stuff.
//what I've tried:
void sayPhrase(const uint8_t *phrase){
  int open = 0;
  for (size_t i=0; i<sizeof(*phrase); i++){

      if(pgm_read_byte(*phrase) != 4 && open == 0){
          Serial.println("mouth open");
          open = 1;
      } else if(pgm_read_byte(*phrase) == 4 && open == 1){
         Serial.println("mouth closed");
         open = 0;
      }
      say(pgm_read_byte(*phrase+i));
    }
}

But when it comes to passing a static const I'm lost I've tried passing it as a reference with * but nothing I do seems to work - I just don't know the proper way to do this in C.
What I have compiles, but it seems to only get one phoneme and repeat it over and over. The rest are lost.

The problem is, when you call sizeof(*phrase), what is returned is 1, the size of the uint8_t array element, the result of your pointer de-reference. On the other hand, if you call sizeof(phrase) inside the function, you get the size of the pointer itself and not the size of the array, as you might expect. When you pass the array to the function via a pointer, the function has no idea if you passed the start of an array to it or merely a pointer to some uint8_t variable, so it can't know what the size is; context has been lost.
Instead, you should call sizeof(phrase) in the same scope where the array was declared and initialized and pass the result to the function, which can then use this value in the for loop.
static const uint8_t PROGMEM heybuddy[] = {
  pPA5, pHH1, pEY, pPA5,
  pBB2, pAX, pDD2, pIY, pPA5,pPA5,pPA5,
};

size_t SIZE = sizeof(heybuddy);  // this is ok since each element = 1 byte

sayPhrase(phrase, SIZE);

The function definition should be:
void sayPhrase(const uint8_t *phrase, size_t size){
  int open = 0;
  for (size_t i=0; i < size; i++){

      if(pgm_read_byte(phrase) != 4 && open == 0){
          Serial.println("mouth open");
          open = 1;
      } else if(pgm_read_byte(phrase) == 4 && open == 1){
         Serial.println("mouth closed");
         open = 0;
      }
      say(pgm_read_byte(phrase+i));
    }
}

Thanks! It didn't work using
say(pgm_read_byte(*phrase+i));
But it worked using:
say(pgm_read_byte(phrase+i));
I guess I'm still not clear on the difference between phrase and *phrase inside the function

@RampantCreativeGroup Oh, I didnt notice that in the body of the function. Copy and paste. phrase is the pointer, the address of the first element of the array. *phrase is the element pointed to by phrase. If you want to use pgm_read_byte(), it means you want to read a byte from some address in flash, so it makes sense to pass the pointer, phrase, but not the first array element, *phrase.

I have some extensive examples of accessing PROGMEM here.
I've adapted one of the examples to show how you might do something similar to what you want:
const int NUMBER_OF_ELEMENTS = 10;

const char Message0000 [] PROGMEM = "Twas bryllyg, and ye slythy toves";
const char Message0001 [] PROGMEM = "Did gyre and gymble";
const char Message0002 [] PROGMEM = "in ye wabe:";
const char Message0003 [] PROGMEM = "All mimsy were ye borogoves; And ye mome raths outgrabe.";
const char Message0004 [] PROGMEM = "\"Beware the Jabberwock, my son! \n The jaws that bite, the claws that catch!";
const char Message0005 [] PROGMEM = "Beware the Jubjub bird, and shun\n The frumious Bandersnatch!\"";
const char Message0006 [] PROGMEM = "He took his ";
const char Message0007 [] PROGMEM = "vorpal sword in hand:";
const char Message0008 [] PROGMEM = "Long time the manxome foe he sought - ";
const char Message0009 [] PROGMEM = "So rested he by the Tumtum tree, \n And stood awhile in thought.";

const char * const messages[NUMBER_OF_ELEMENTS] PROGMEM =
   {
   Message0000,
   Message0001,
   Message0002,
   Message0003,
   Message0004,
   Message0005,
   Message0006,
   Message0007,
   Message0008,
   Message0009,
   };

void sayPhrase (const char * const * message)
  {
  const char * ptr = reinterpret_cast<const char *>(pgm_read_ptr (message));  // pointer to message
  Serial.println(reinterpret_cast<const __FlashStringHelper *>(ptr));    // and print it
  } // end of sayPhrase

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

  for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
    sayPhrase (&messages [i]);

  }  // end of setup

void loop () { }

It's better to use pgm_read_ptr rather than pgm_read_word because it expresses the intent better and doesn't rely on the assumption that a pointer is the same size as a word. (It usually is the same size as a word, but that may not be true for all boards.) Additionally, rather than performing an unncessary copy, you could take advantage of Arduino's __FlashStringHelper type.

Sounds sensible enough. The original (which makes a copy) might be more general (you might need the string in a context where the __FlashStringHelper type doesn't apply), but I accept your suggested changes.

If you're not averse to a bit of C++:
void sayPhrase(const uint8_t * phrase, size_t size)
{
    bool open = false;
    for (size_t i = 0; i < size; ++i)
    {
        if(pgm_read_byte(phrase) != 4 && !open)
        {
            Serial.println("mouth open");
            open = true;
        }
        else if(pgm_read_byte(phrase) == 4 && open)
        {
            Serial.println("mouth closed");
            open = false;
        }
        say(pgm_read_byte(&phrase[i]));
    }
}

template< size_t size >
void sayPhrase(const uint8_t (&phrase)[size])
{
    sayPhrase(phrase, size);
}

Which can then be called directly on the array:
sayPhrase(heybuddy);

And the template will infer the array size and call the non-template function.

As others have pointed out, your problem is sizeof, which is calculated at compile time, not when the code is run.
You need to pass the size of the array to the function. This can be done in many ways, depending on what else you are doing.
In c the most common method is to use a null-terminated string, but I suspect this may not work.
You can store the size of each phrase in a separate array, and pass as a separate parameter or Pascal style as a count byte in the first element of the phrase.


text:
MP3 Shield stacked on DMX Shield - Arduino Uno
We are using Arduino Uno revision 3, with TinkerKit DMX Shield rev. 4 and Sparkfun Mp3 Shield.
We uploaded the Mp3 Shield example called FilePlayer and after we open the serial monitor, the interface is there and working. The problem is that it won't output the music from the SD card.
If we ONLY stack the Mp3 Shield onto Arduino, it works.
Is there some king od incompatibility between the DMX and Mp3 Shield, and if there is, what would be the solution, maybe some kind of bypass, since we aren't that familiar with what pins the DMX shield uses for it's purpose. ATM the Tinkerit site is down so we can't acess the TinkerKit DMX Shield datasheet.

Yes, overlapping is a problem, by default the MP3 Shield uses digital pins 2(DREQ),6(mp3CS),7(mp3DCS),8(RST),9(SD-CS),11(MOSI),12(MISO),13(SCK)
The Tinkerkit DMX Master Shield R4 uses 2(RE-ENn),3(VTX),4(VRX),5(DE-EN),6(D6)
So there are conflicts with D2 DREQ vs RE-ENn and D6 mp3CS vs D6.
The DMX Master Shield basically converts the UNO's serial to DMX. If nothing is at first included into the Sketch for this, then the problem is with only D6. Leave this jumper OFF. And I suspect the MP3 Shield will work stacked.
To use them together you can move the pins, as demonstrated at https://www.youtube.com/watch?v=behMgV3tUr4. Noting that is for different pins. And of course you will need to subsequently change their definition, in the sketch.

We swapped pins D2 -> D5 and D6 -> D10 following your tutorial, changed the input declaration in the SFEMP3ShieldConfig.h script and after we plugged in everything it still didn't play (Arduino , stack DMXShield and MP3Shield). We removed the DMXShield and stacked just the MP3Shield (still with the bypass), and in the interface used the BEEP test, and it works. But the music from SD card is now playing just for 1 second and stops.

Please note that D2 on the Arduino UNO is a interrupt pin for INT0. The default behavior of the SFEMP3 shield's library is to use interrupts. As per your YouTube comment you moved D2 of the SFEMP3. I would not recommend moving this wire. As it must be moved to another INTx pin. And on the UNO that is only INT1(D3). Rather I would recommend moving the DMX shields with this technique to pins not used by the SFEMP3 shield. That is why it plays 1/2 second and stops there is no IRQ to do a refill. Did you leave the D6 jumper OPEN? that is likely the hot problem, blocking the SdCard.

I would recommend a simple Debug technique of using jumper wires. Stack the MP3 on top of the UNO and Jump all the wires from the MP3 to DMX. This emulates it being stacked. Then start pulling wires until it works. Or the opposite. start with just GND and VCC and then add wires until it stops. Bingo you will know what broke it. and then can learn from the schematics as to why. I have learned very little from what works. But much more from what does not.

Thx for the continuous support. It still doesn't work, but your advices have been very educational. We did as you suggested: we wired the MP3 interupt pin (D2) to the D2 on Uno. And instead, made the bypass from D2 to D5 on the DMX shield. As for the D6: we wired the MP3 D6 to Uno D6, and bypassed DMX D6 to D10. All of this to prevent the DMX from getting into the MP3's wheels. To answer you question, no, in any of our attempts, the D6 was never "cut-off" without being wired to another pin). Although the serial monitor didn't show any errors, the beep sound test and track made no sound.

We had also tried using Analog pins for bypass since on the MP3 shield, according to Sparkfun's docs., pins free to use for other than the MP3 itself are just D5 and D10 + the analog ones, and always the same story: MP3 alone works as it should, but as soon as we bring in the DMX it stops working. On the side note, the DMX always work as he shuould, bypass or no bypass. No problems there. Our next step is the Debug technique as you recommended, to find exactly where the conflicts happen. Maybe there is  something more that the DMX uses, other thanD2 and D6? Will post results tommorow.

We solved the communication problem! The conflict was only on D4(VRX) with the DMX Shield, we used the Debug technique and started with just the GND and VCC,, started to add wires. D4 is apparently the only one blocking the MP3 Shield from playing the song. In our Script for the DMX Shield we added the function to play the song for the MP3 Shield and it worked. Thank you for the support!

Hmm. I see d4 affects the boot mode of the vs1053.

yes, D4 needs to be LOW as to put the VS1053 into MP3 mode. HIGH will put it into Real Time MIDI mode. The Tinkerkit DMX Master Shield uses D4 as the Receive from RS485 and drives it into the D4 of the Arduino. Where RS485 is normally HIGH, jamming the VS1053 into MIDI mode. Remove R6 of from the Tinkerkit DMX Master Shield. And jumper the center of the RX-SEL to any available pin on the UNO. THen when you define your SoftwareSerial port use that pin instead of 4 as the RX.


text:
How to Write a function or Loop or program to receive fixed number of Integers or characters over Serial?
I am want to receive a 5 character hexadecimal input from user over serial port of arduino Uno.
int count = 0;                                    // count = 0
char userInput[5];

void setup()
{
  delay(1000);
  Serial.begin(19200);                            // begin serial port with baud rate 9600bps

}
void loop()
{
  if (Serial.available() > 5)
  {
    Serial.read();
  }

  else if (Serial.available() < 4)
  {
    Serial.read();
  }

  else if (Serial.available() == 5)
  {
    for (int i = 0; i < 5; i++)
    {
      userInput[i] = Serial.read();
    }

    Serial.print("User Input - ");
    Serial.println(userInput);
  }

  delayMicroseconds(10000);
}

But I want to discard the input if user inters less than 5 characters or more than 5?
Since the Serial.flush() have a different meaning now, I can not clear the buffer if user enters less than or more than 5 characters and the characters gets added to next input.
e.g. If I upload above program and entered input in following sequence:
abcde
abcd
abcd
abcd
abcd
abcdef
abcde

I got the following output:
User Input - abcde
User Input - dabcd
User Input - dacbd
User Input - bcdef
User Input - abcde

Two invisible characters appear in output which are not visible but when I copied the output from serial monitor but these characters appear when I copy paste the output into Text Editor.
So How can I modify the program to receive only 5 hex character input from user (Which user will input from Hex Keypad)? And if user enters more or less character I want to clear the input buffer for next user input so that characters from previous input doesn't get added to next one.

Does your keypad or data-entry procedure have an "enter" or submit or other termination indicator which, or is your program supposed to react at the moment the 5th character is pressed/entered? In other words, is there a way for the user to indicate "I'm done" entering characters?

Right Now I test testing this Program on Arduino IDE on Laptop over Serial Monitor.

So right now on IDE I am Pressing "ENTER" key  on laptop keyboard to indicate "I'm Done"
But in future I will modify the program to auto react when 5th character in entered..

The solution now I seek is, How to receive only 5 Character input and reject smaller or bigger input?

You need something to synchronize. You need to know where the begin is of the 5 characters. It can be very simple, for example a 'stx' or a '[' character. Or you can use a character at the end of the 5 characters, for example a carriage return or line feed. If you have no control over the serial keypad, then you can use timeouts to identify the start of the 5 characters. In that case you have to describe very careful all the timeouts and the data.

As noted in the comments, since your prototype is receiving data from the serial port, you need some way for the user to indicate to the program that they are finished entry, since a 4-character entry is a necessary point along the way to a 5-character entry.
What you are doing now, by checking if Serial.available()>5 is letting the serial buffer hold 6 characters before you read from it (note: 5 is not >5), but then your else statement:
else if (Serial.available() < 4)
{
  Serial.read();
}

Clears out the buffer (Serial.read() removes one character from the buffer), so you will never get to 5 characters anyway, unless all 6 characters come in between runs of loop(), which is not likely at 19200 baud.
Not to mention that while data is sitting in the buffer, you don't know what it is and can't act on it. It is better to use the buffer as intended, which is to allow the Arduino to collect serial data, even while your program is working on other things, and then grab any pending data from the buffer as the program loop()s.
You have declared the userInput[5] array to hold user input, but note that if you only declare it at 5 chars long, it cannot hold the null-character terminator that is standard for C-style strings. It would be better to declare this as:
char userInput[6];  // Holds 5 user characters, plus null terminator.

In your loop(), you should copy out the contents of the buffer into your userInput, check the length or for a termination character, such as a carriage return or newline (i.e., pressing 'Enter' on the serial terminal.) and act accordingly. Here is an example, showing just the relevant bits for the user input and hiding the rest in [...]:
char userInput[6];  // Holds 5 user characters, plus null terminator.

void setup() {
  userInput[0] = '\0';  // Initialize string to empty
  Serial.begin(9600);
}

void loop() {
  uint8_t processInput = 0;   // Set to 1 if we have complete entry
  while (Serial.available()>0) {
    char input = Serial.read();
    if (input=='\r' || input=='\n') {
      // Have received a terminating character,
      // Flush the rest of the buffer
      while (Serial.available()) {
        Serial.read();
      }

      processInput = 1;

    } else {
      int s_len = strnlen(userInput, 5); // Get current length of userInput
      if (s_len<5) {
        userInput[s_len++] = input;      // Append character
        userInput[s_len] = '\0';         // Null-terminate string
      } else {
        // User has entered more than 5 characters and no terminating
        // character; here is where you can decide to clear the userInput
        // and start over, or just drop the first character and care
        // about the most recent 5, etc. Here, we will clear the input
        // and start over; The 6th character is dropped/ignored and
        // user input starts again. It is as though the 6th character
        // entered is like pressing Enter, but it does not process
        // the incoming data, beacuse 6 characters is an invalid input.
        userInput[0] = '\0';
        s_len = 0;
        processInput = 0;
        // Invalid input
        Serial.println("Error: invalid data");
      }
    }
  }

  if (processInput) {
    Serial.print("User input - ");
    Serial.println(userInput);

    if (strnlen(userInput, 5)==5) {
      // Do something **here** with the input string!!

      // Reset input string
      userInput[0] = '\0';
    } else {
      // Invalid input
      userInput[0] = '\0';
      Serial.println("Error: invalid data");
    }
    processInput = 0;
  }
}

Note, this code is not fully tested and may contain bugs. In particular, I did not intensely check if the while (Serial.available()) {} properly handles a lot of extra data.
One final note, you don't need the delay() with this code.
EDIT:
I tried the sample code above and it had a couple of bugs, one of which was that after a successful 5-digit entry, the input string was not reset to empty. I have now updated the code and it's a valid, working program to receive and process a 5-character input on the serial port and to toss an error if fewer than 5 or more than 5 characters are entered. Entry is terminated with a carriage return or newline (enter key).

else if (Serial.available() < 4)
{
Serial.read();
}
Sorry it is < 5. Now Program rejects all entries below 5 characters. But if user enters more than 5 characters the 1st character is neglected and only 5 characters from 2nd to 6th characters are printed.

Thanks for the answer.. I will try your suggestions with delay and other necessary edits..

I wrote following program, it receives 5 character input from user and if user enters input more than 5 characters then program store only 1st 5 characters and if user inputs less than 5 characters long the it rejects than input altogether..
char userInput[5];
void setup()
{
//delay(1000);
Serial.begin(9600); // begin serial port with baud rate 9600bps
}

void loop()
{
if (Serial.available() < 5)
{
   Serial.read();
}
else if (Serial.available() >= 5)
{
      for (int i = 0; i < 5; i++)
      {
        userInput[i] = Serial.read();
      }
     while (Serial.available() > 0)
     {
       Serial.read();
     }
Serial.print("User Input - ");
Serial.println(userInput);
}
delay(100);
}

Not only does it assume user input always comes in a single block, anything less than a full block of 5 characters gets thrown in the garbage and is lost forever.


text:
Rename device name (ch340 usb to serial) Mac OS
Can't upload sketches to Arduino Nano clone with USB to serial chip ch340.
After installing drivers and plugging in, device has the name cu/tty.wch ch341 USB=>RS232 fa130 (with spaces), but Arduino can't recognize the full name (only tty.wch).
Is it possible to rename device in Mac OS or change device identifier?
UPDATE: ch340 new driver http://www.wch.cn/downloads.php?name=pro&proid=178

Found driver that works and after installing gives proper name for device. If you have WCH ch34x chip on arduino and get error "can't open device "/dev/tty.wch" or "/dev/cu.wch" in Arduino IDE, this should help http://goo.gl/EmN4IH (Dropbox)

I was going to suggest a symbolic link (e.g. in terminal ln -s /dev/tty.arduino "/dev/tty.wch ch341 USB=>RS232 fa130" but I tried it and it didn't work. Good you found a solution.

I expect a symbolic link would work, but creating it may require admin permissions, and that complicated a name could require escaped characters.

Does this work on El Capitan? The device disappeared after upgrade.

Which version of OSX was this for?

I used a terminal command:
sudo ln -s /dev/tty.wch\ ch341\ USB\=\>RS232\ 1450 /dev/tty.USB0

where /dev/tty.wch\ ch341\ USB\=\>RS232\ 1450 is the original name not recognized by Arduino; and /dev/tty.USB0 is the new port name.

You don't have to escape the spaces, rather, put everything in double quotes.

The drawback is that after disconnecting the drive it also removes the symlink :-?

I am Antonis from codebender and we recently released drivers for the Mac.
If you want to overcome this problem, without disabling your computer's security settings, maybe I can help you with this! Codebender just released their Mac drivers package, which includes a new driver that supports the CH340G chip, on Yosemite and all other versions of OS X for Mac.
This will help you to install these drivers securely, and
all you have to do is to download and install them.
You can find more information about the drivers in the codebender blog.

Can your driver be used by the regular Arduino IDE, or does it only work with Codebender?

Loading  codebender and its drivers (ch341 driver in particular)  fixed my strange problem where only my old Arduino 1.05 IDE would work with my ch340 UNO and the the 2.0  (1.6.7) would not.  Thanks.  And it works in the browser as advertised.

Worked very well for an unrecognized clone board ! Thanks

I send email about this issue to WCH, and they change drivers to the latest version on their website, this is direct link http://www.wch.cn/downloads.php?name=pro&proid=178 (driver works and device has proper name in dev/)

Nice try. But actually the driver still creates that rotten name /dev/tty.wch ch341 USB=>RS232 fd130

Have to take back that comment. The new driver seemed to need some restart (log off/on) to activate and now creates /dev/tty.wchusbserialfd130. Cheers!

For Yosemite you seem to need to run this command in the Terminal and then restart the computer to get it to work.
sudo nvram boot-args="kext-dev-mode=1"

@ChristianJuth With this command, you enable non-approved drivers to work on newer OSX versions such as Yosemite.

I was having the same problem. installed the latest drivers, I'm using yosemite, installed the Arduino IDE, and tried the board in windows 7 and it worked in windows, so board and cable are working.
In mac OS 10.10 in system report now they show as USB 2.0 Serial in arduino IDE it appears the port now (only after I used the SUDO command that sjunnesson posted) /dev/cu.wchusbserialalpha1310
so, use the sudo command if you are in yosemite

once you have installed the driver, you should be able to use it with any IDE or program
but I doubt anyone would prefer the Arduino IDE to codebender


text:
Arduino Uno R3 board dead
I have an arduino uno Rs board and when connected to USB the board is dead. Yet when connected to the external supply the board will come to live. Power LED on and led near pin 13 blink on and off all time. I tried another computer and other new usb lead. Still computer will not see the board. When usb lead is on checked the 5 volt on the board and it is ok. Even checked the usb lead with multi meter and all  four connection are ok
Can you give me some advice

1.Yes I bought the new board from different source but still waiting for it to arrive.
2.  My clone board Arduino uno using microcontroller Atmega329P-PU and interphase chip Atmega16U2]
3 but the video link is still of help as my new board is as the one shown in the video. Will use it late. Great!!!
There should be a similar explanation for the one I have in the picture

When connected by USB, does the LEDs light up? Or is it only that the PC cannot find it?

Using the usb only board to computer  the board is dead no led comes on and computer does not see the board. Only when external 12v is applied in the dc socket the power LED comes on and led near pin 13 start blinking. But computer still does not recognize the board.

So basically two problems?
Not being powered by USB
AND not being recognized by PC?
You should check if these things are related. If it never worked before, it might just be a bad board. You can try programming with a regular AVR programmer.

Does the Arduino show up at all in device manager or in mac/linux.(not sure what you are using)Is your board authentic or a clone? Did this happen the first time you plugged the arduino in or after uploading sketches etc? I had screwed up my firmware for my board that acted similar to what you describe.(I was trying to flash a different firmware) Eventually i ended up reflashing the right firmware and it went back to working again.Maybe it's that, maybe it isn't.

I am using window 7 . It says on the board made in Italy but I doubt it. I think it is a clone due the power led is red not green and the small chip near the usb is green not brown. But a lot of these boards work. Yes this happened first time I plug the usb in. How can I reflash the right filmware. I like to try your idea. Maybe it work. Thanks

I think you will need a working Arduino / usbtinyisp v3.0 or a usbasp programmer (I'm sure there are more options but that's what i know that works) I have read where people who bought the clones had faulty flashes on them when they get it.  Also the chipsets are different so you may have to do some research on that. The link that 'Matt' Posted would be a good starting point in learning how to reflash firmware.

I had a similar problem. though it was easily solved but not obvious.
I couldn't connect my nano to the computer, but other devices worked fine. After a while other devices started to be faulty such as portable hard-drives and my CC3D flight controllers. After a cable replacement all the items started working again even the Arduino that i otherwise had discarded as broken.
It might not be the solution you are looking for but im leaving it here in case others comes for a solution.

You are happy the lead is ok. Good.
Can you test another Arduino on the PC? (Is it a driver issue?)
Can you connect to the serial pins on the Arduino and read the console output, is anything coming out on USB? (Is the USB socket on the board broken?)
Have you selected the right board type on the ide? (I know it's a dumb question but...)

I only have one arduino uno and bought another but still waiting for it to arrive. But if this is a driver issue a the computer still should recognize the board. When a new device is insert in the computer it should detect and say in the device manager "unknown device" up to my little knowledge. I must find a way how my computer see this new device.The usb on the board is solid and measured the 5volts the ok. But do not know how to measure date. maybe will put an oscilloscope.

Did you buy the second board from a different place? Otherwise you may have the same problem.

I don't agree with the title of this, but this MIGHT help
http://www.instructables.com/id/How-to-fix-bad-Chinese-Arduino-clones/


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

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

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

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

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

There is also an unsigned variant, strtoul.

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

replace the utf-8 conversion

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

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

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


text:
Arduino Yun, pass int data true REST
Would it be possible to instead of passing a state via a REST browser:
digital/13/1

to set an int value? For example, if in the sketch if I would name an int: 2, could I set this to 48 via REST?
If so, how?

Just to be perfectly clear, it is illegal in C++ to have a variable name start with (or be) a number.

Check out the TemperatureWebPanel example: you'll see that you can make your own REST APIs and pass any values your sketch can handle.


text:
Beginner Arduino Project: Drumming Robot
So, I've got a music degree, 5 years programming with Ruby and 7 with Pure Data. I've also got hold of an Arduino and a Raspberry Pi.
Anyway, I've seen a number of Arduino projects which involve firing events which cause a stick to hit a drum, but I really don't know where to start.
I have a wicker penguin that I want to have play the drums:

What components do I need to produce this kind of one-off percussive event?
Can I trigger these events from Ruby?

Welcome to Arduino SE! I edited your question a bit, removing the request for tutorials. Stack Exchange is a repository of information, not a repository of links. If you have any questions, please feel free to reply to this content. Thanks! (Also, penguins are awesome :-D)

I'm not sure about removing the last sentence, as it explains what the penguin image is for, but it appears I can't edit that part of it with a rep of 101.

Fixed that, apologies.

I think the most challenging part of this project will be coming up with an electro-mechanical mechanism which moves the arms in a good drumming motion, without depending on an expensive, power hungry industrial servomotor and driver.  A sensor-equipped brushless motor off a large RC car might work well, but finding or creating a suitable controller could be a challenge.

On a smaller scale you could try a solenoid and a spring... unless you happen to have one of the huge ones from a mainframe removable-platter hard disk mechanism (I once saw such driving a rocking chair!)   Some combination of a motor, cam, arm with a return spring, and an encoder for position and speed feedback might also work.

The approach I would take for the arms is to use a servo motor as these are fairly cheap and are closed loop so you don't have to add any extra sensors to check where the current position is.
Types of Motors:

Stepper motors are a type of motor with a special arrangement of coils that allows you to turn a fraction of a degree by sending pulses to the motor. For example, you can buy a 200 step stepper motor that turns in increments of 1.8 degrees. These are somewhat expensive and require somewhat expensive drivers (usually $5-10 per driver). Often used in CNC machines and 3D printers. Continuous rotation.
General DC motors (two types: brushless and brushed, but I won't get into that in here) are a type of motor. Their drivers are often cheaper than one for a stepper motor, but you have little control over their rotation (instead of "take one step which is X degrees," you say , "turn at 25% power clockwise," where you don't know the actual speed). These are sometimes used with rotary encoders or potentiometers to control the speed and position of the spindle. Continuous rotation.
Servo motors are actually not their own type of motors; they are DC motors (not steppers) with a potentiometer built in along with the driver. You send pulses to it (you can use the Arduino servo library for this) to tell it the exact degree to go to. Can only go a limited range: usually either 90 or 180 degree, although you can get special ones that can turn much longer ranges than that.

Using a Servo Motor:
You can hook it up like this:

From this Arduino Tutorial

And then some very simple code to use the motor:
#include <Servo.h>

Servo myservo;

void setup() {
  myservo.attach(9);
}

void loop() {
  myservo.write(10);
  delay(500);
  myservo.write(0);
  delay(500);
}

Talking with Ruby:
Your best option is to use the serial port on your computer. Figure out how to access a COM/serial port in Ruby. You can then send messages from your computer to the Arduino, but you'll have to figure out a way to structure the messages.

This may work for limited purposes, but a typical RC servo has a relatively slow transit time which will limit achievable tempo.  I'd also be concerned about damaging the gears unless there is a fair amount of flex in the mechanism - which may be needed also in order to let the stick or mallet spring back enough to avoid deadening the sound.

@ChrisStratton the stick height would have to be pretty small (although that may make it to quiet, although I doubt many people would have an objection to a drummer wicker penguin being quiet). Also, I don't think it's the OP's expectations to have it play thirty-second notes at 150 BPM, but you're right that a more powerful servo will be needed. In addition, the OP might want to have it "grip" the sticks towards the middle so it doesn't have as much pressure as the sticks act as levers.

I really don't think they would get much sound without a whipping action from driving a longer, flexible stick.   I will grant they are faster than I remembered though: say .2 seconds each way, so with care to time the commands just right 120 BPM quarter notes might be achieved.

Thanks, this looks like a really handy primer for motor components. On the Ruby interaction part, does this mean I should create functions in the arduino syntax, upload them to the arduino, then trigger them from Ruby using the serial port?

@ChrisStratton .2 each way would yield eighth notes at 150 clicks (60 seconds per minute / .4 seconds per hit = 150 hits a minute with 2 sticks = approx. 150 BPM eighths)

It may be possible to get it above 120, but I was leaving some allowance for the fact that the device commanding position doesn't know when the previously commanded position has actually been achieved.  It will vary with voltage though, so running the servo at the highest specified voltage may help.  And of course there are faster servos available at a premium.  I do worry about the gear noise.

to move the arms: look for tutorials about arduino controlling a motor (either step od DC).
to control the arduino from a PC (or the PI) - that's what it means when you say Ruby - check how to remote control over serial port

If you want to have a look, I did something similar in python.
Ii emulates a USB keyboard, but you can add more commands to support the control of the motors.
https://github.com/01org-AutomatedFlasherTester/pem

I'm not sure if this is the answer yet, until I can spend a bit of time on it, but it looks like the serial port control is probably going to be the correct approach.


text:
Cannot find solution to "variable out of scope"
First C program. Spent a lot of time looking for a solution. KeyPad produces 'char' instead on 'int'.  Plus I want to display 'End', thus I wrote the 'main' to to support 'char' and thus had to adapt a 'char' to 'int' conversion work around, line 89  Certainly there are other errors.
extern "C"
// Microwave ccp

  #include <Arduino.h>
  #include <stdlib.h>
  #include <string.h>
  #include <inttypes.h>
  #include <Keypad.h>
  #include "TM1637.h"
  #include <TimerOne.h>
class TimingISR
{
public:
    TimingISR();
    bool Enable_interrupts, Disable_interrupts;

  char lead_char, unit_sec, tens_sec, num_min;
  int int_unit_sec, int_tens_sec, int_num_min;
  int Count_Seconds, Remainder, brightness = 4, PowerLevel;   //BRIGHT_TYPICAL = 4, BRIGHT_DARKEST = 0, BRIGHTEST = 7
  bool Colon, PointFlag, Points_enable;
  char data_char;
};

// these are all Clobal Variables
  int pin_Clk = 2; //  or 3 for IC2
  int pin_DIO = 3; //  or 2 for IC2
  int PIN_RELAY = 4;  // controls power on/off to 'cook'
  int PIN_Beeper = 5; // PWM beeps when finished

  int  pos, Remainder, num;
    // Timer variables
  char tempchar;

  // Read Key Pad, continuously
const byte ROWS = 4; // Four rows
const byte COLS = 3; // Three columns
char lastkey;
char keys[ROWS][COLS] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'#','0','*'} };// Define the Keymap
byte rowPins[ROWS] = { 9, 8, 7, 6 };  // Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins.
byte colPins[COLS] = { 12, 11, 10 };  // Connect keypad COL0, COL1 and COL2 to these Arduino pins.
Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );  // Create the Keypad
#define ledpin 13
void setup()
//        Colon = OFF;   PointFlag, Points_enable   ***************************not coded yet
{
  pinMode(ledpin,OUTPUT);
  digitalWrite(ledpin, HIGH);
  Serial.begin(9600);
}
void loop()
{    // run repeatedly

   char key = kpd.getKey();
   // if ((key = NO_KEY) || (lastkey = key)); delay(100); exit(0);    }

 {  if (key)  // Check for a valid key.
      switch (key) {

      case ('0'): case ('1' - '0'): case ('2' - '0'): case ('3'-'0'): case ('4' - '0'):  case ('5' - '0'): case ('6' - '0'): case ('7' - '0'): case ('8' - '0'): case ('9' - '0'): //all key integers
 { if ( Count_Seconds > 0 ) // Cooking in progress, thus SHUT DOWN, any numeric key shuts down the power
  {  lead_char = 'C';
     num_min=    'n';
     tens_sec=   'C';
     unit_sec=   'l';
goto CancelPower;
  } //  Short Delay, then Display “A000”
    else
  {     num_min = tens_sec;  // integers: update the 'time' 'stack' as integers
        tens_sec = unit_sec;
        unit_sec =  (key-'0');  // '0' = 30 base 10 etc
        lastkey = key;
        Colon = ON;
goto DisplayAll;   // accumulate time value  // any old num_min_segment fall off
  } }     //
  break;  //---------------------------------------

      case ('#'-'0'):  // Start Heating
      if (lead_char != 'A')
goto OOPS ;
       else  // convert time parts to Count_Seconds
        (  Count_Seconds = int(unit_sec) + int(tens_sec) * 10 + int(num_min) * 60  );
  {       if  (  Count_Seconds > 0 )
TimingISR(  ) ;
          lead_char = 'c'; //  ’c’ooking
          Colon = ON;
          pinMode(PIN_RELAY, OUTPUT);
          digitalWrite(PIN_RELAY, HIGH);  // turn on the heat
          PowerLevel = 10;
  }
   break;  //---------------------------------------

      case  ('*'-'0'):  // Set Power level or default DEFROST Power level
     //unit_sec_segment = a number as a 'segment' value    // a power level manually inserted
{   if ( lead_char ==  'A'  &&   num_min == '0' &&  tens_sec == '0' )
{    if ( unit_sec =  !('0') )         // &&  unit_sec > '0' && unit_sec <= '9' )
 {      int PowerLevel = aoti(unit_sec);
        lead_char = 'P';    //Display "P=n0", n = percent power via duty cycle
        num_min =   '=';
        tens_sec = unit_sec;  //display 'char' as 10's 'percent' value, move number left one place
        unit_sec =  '0';  // insert a zero
 }   else  // power not manually set
 {      PowerLevel = 2;     // 'defrost' = 20 %
        lead_char = 'd';
        num_min =   'E';
        tens_sec =  'F';
        unit_sec =  '_';
 }
goto DisplayAll;
}
   else
//    if ( lead_char != 'A'  ||  num_min != '0' ||  tens_sec != '0' || unit_sec !=  '0' )
goto OOPS ;
}     //end if, of Case “*"
      break;  //---------------------------------------

   lastkey = key;
delay(100);  //100 millisec
}   // End Of Switch Key
}  //  End of If (Key)
//return

// Beginning of GOTO's--------------------------------------
{
OOPS:
     lead_char = 'o';   //Display "ooPS"
     num_min =   'o';
     tens_sec=   'P';
     unit_sec =  'S';   // then Short Delay, then Display “A000”
CancelPower:
      pinMode(PIN_RELAY,OUTPUT);
      digitalWrite(PIN_RELAY, LOW);  // turn off the heat
goto DisplayAll;  //ready to accumulate 'heating' time input
    delay (3000);     //let it display for 3 Count_Seconds, then clear the display
    lead_char = 'A';        //ready to accumulate 'heating' time input
    num_min =   '0';
    tens_sec =  '0';
    unit_sec =  '0';
    Disable_interrupts;
    int Count_Seconds = 0 ;
DisplayAll:

// DisplayAll:  //Would like to put this into the 7 segment display
 // Address each 7 segent unit, one after the other; left to right
{    for ( pos = 0 ; 3 < 4; pos++);
      if ( pos = 0 )
        char_data = lead_char
      if ( pos = 1 )
        char_data = num_min
      if ( pos = 2 )
        char_data = tens_sec
      if ( pos = 3 )
        char_data = unit_sec

if ( char_data='0') ; num = 1; // the 7 segment display 'h' only allows for integers 0 through 15, i.e. HEX characters
if ( char_data='1') ; num = 2;
if ( char_data='2') ; num = 3;
if ( char_data='3') ; num = 4;
if ( char_data='4') ; num = 5;
if ( char_data='5') ; num = 6;
if ( char_data='6') ; num = 7;
if ( char_data='7') ; num = 8;
if ( char_data='8') ; num = 9;
if ( char_data='9') ; num = 10;
if ( char_data='A') ; num = 11;
if ( char_data='B') ; num = 12;
if ( char_data='C') ; num = 13;
if ( char_data='d') ; num = 14;
if ( char_data='E') ; num = 15;
if ( char_data='F') ; num = 16;
if ( char_data='c') ; num = 17;
if ( char_data='H') ; num = 18;
if ( char_data='h') ; num = 19;
if ( char_data='I') ; num = 20; //left vertical 2 segments
if ( char_data='i') ; num = 21;
if ( char_data='L') ; num = 22;
if ( char_data='l') ; num = 23; /right /vertical 2 segments
if ( char_data='n') ; num = 24;
if ( char_data='O') ; num = 25;
if ( char_data='o') ; num = 26;
if ( char_data='P') ; num = 27;
if ( char_data='r') ; num = 28;
if ( char_data='S') ; num = 29; //same as a five
if ( char_data='U') ; num = 30;
if ( char_data='u') ; num = 31;
if ( char_data=' ') ; num = 32;
if ( char_data='=') ; num = 33;
if ( char_data='-') ; num = 34; //dash / minus
if ( char_data='_') ; num = 35; //under score
if ( char_data='[') ; num = 36; /left /bracket
if ( char_data=']') ; num = 37; //right bracket
// there are other usefull, such as "top score", "middle score... "top minus", "bottom Minus",
// which yoou could assign some other othervise unprintable character as a proxy, e.g  the ampersant to display a "top position minus sign"

}
Disable_Interrupts;
  TM1637DisplayAll(uint8_t num, uint8_t pos);
Enable_Interrupts;
}
return(0)
}
}  //  End of void LOOP()

//--------------------------------------

// ----------------------------------------------------

"Auto Format Canceled: too many right curly braces" says the Arduino IDE. Your code has quite a few problems, and it can't compile as is.

I totally had to stop reading... You should first learn how to write a program before trying to make a complicated program like this. Indentation, parentheses, comments are used to make the program more readable and easier to understand, for both us and you. Then in this program I see a lot of problems: you should not define classes inside the main .ino file, but have a header (.h) file with the declarations of the members and a source (.cpp) file for the implementation. A couple for each class. And... I highly suggest you to use the modular approach (i.e. write a piece of the program, test...

... it, then write another one, test it again, until you added all the features). Writing all the program at once (or worse copying and pasting pieces from other programs) without testing them when you add will lead to this: an unfixable mess of compiling errors and bad behaviors. Divide et impera! For instance: 1) communicate through serial 2) read the keypad and write to serial 3) read from serial and display 4) join the jeypad and display, ... And, please, use 8-bit (uint8_t or byte) variables whenever possible, and make constant values (like pin number) constant; your uC will thank you

You have a pointless class defined, there is no need for a class for that. 2) if ( char_data='u') ; num = 31; will set char_data to 'u' and num to 31. == not = for a logical comparison and skip the first ; in those lines. 3) goto is EVIL. There are a few situations when it's use can be justified. This isn't one. 4) case ('1' - '0'): should probably be case '1': And that's just from a very quick skim through the code.

@frarugi87 - This is a way of learning, yes its riddled with bugs but its a start, you sound quite negative about it.

@CodeGorilla It was not my intent, sorry if I sounded too negative but it was just because comments need to be too short, so I have to sum up ;) anyway what I wanted to point out is that rather than writing everything at once and then struggling to fix it it's much better to divide the problem, make small solutions, test them and fix their bugs, then integrate them in one program and fix the interactions. For this particular project I'd start from scratch again, because it is much longer to fix it than to rewrite it

The first line says extern "C" but you haven't scoped it, I'm really not sure what you are trying to achieve or if it will work.  Personally I would remove that line.
"Microwave ccp" come compilers complain if the filename is not right.  As far as I know it should be either .cc or .cpp, but its proably just a typo in the comment, because I doubt you would get this far if it was wrong.
Pins 2 and 3 for I2C, its normally A4 and A5.
Line 58 The reason your commented out code didn't work is (lastkey = delay) you should have used equivalence (==) rather than assignment (=).
Use function calls rather than goto statements, it isn't the 1970s anymore! :)
int(variable) is not casting it is creating an integer from variable and then its disposed of when it goes out of scope.  (int)variable is casting.
for (pos = 0; 3 < 4; pos++); This will cause you problems, because its an empty loop, does nothing, which means pos doesn't have the value you think it does.

Please don't take any of this the wrong way, I'm not a teacher but I need to explain what has gone wrong with you code and how you can fix it.  It is not personal criticism, I bet my first program was ten times worse.
You seem to have a misunderstanding of "variable scopes".  Put simply a variable can only be 'seen' after the point you declare it and within the immediate curly braces {} and all child braces. e.g.:
int GlobalVariable = 1; // Visible through-out the code
void loop ()
{
    int LoopVariable = 2;
    for (int ForVariable = 0 ForVariable < LoopVariable; ++ForVariable)
    {
       ++GlobalVariable;
    }
    Serial.println (ForVariable);  // ERROR
}
void AFunction()
{
    Serial.println(LoopVariable);//ERROR
}

You immediate error is you have defined the variable unit_sec inside class TimingISR and you are accessing it like a local variable.
Now The way you have defined class TimingISR is like designing a car, its fine on paper but you can't drive it until you build one.  As far as I can see you haven't instantiated an instance of TimingISR.  It sounds complex but you have been doing it for int and char (They aren't classes, but its very similar)
int pin_clk = 2;
TimingISR aTimingISR;

If a value should change define it as const.
const int pin_clk = 2;

If it does change you will get a compilation error rather than suddenly sending the I2C clock signal to the on board LED.
goto is evil.
case ('0'): case ('1' - '0'): case ('2' - '0'): case ('3' - '0'): case ('4' - '0'):  case ('5' - '0'): case ('6' - '0'): case ('7' - '0'): case ('8' - '0'): case ('9' - '0'): //all key integers
        { if (Count_Seconds > 0) // Cooking in progress, thus SHUT DOWN, any numeric key shuts down the power
        {
            lead_char = 'C';
            num_min = 'n';
            tens_sec = 'C';
            unit_sec = 'l';
            goto CancelPower;

CancelPower:
        pinMode(PIN_RELAY, OUTPUT);
        digitalWrite(PIN_RELAY, LOW);  // turn off the heat
        goto DisplayAll;  //ready to accumulate 'heating' time input
        delay(3000);         /// NEVER EXECUTED
        lead_char = 'A';     /// NEVER EXECUTED
        num_min = '0';       /// NEVER EXECUTED
        tens_sec = '0';      /// NEVER EXECUTED
        unit_sec = '0';      /// NEVER EXECUTED
        Disable_interrupts;  /// NEVER EXECUTED
        int Count_Seconds = 0;/// NEVER EXECUTED
    DisplayAll:

        // DisplayAll:  //Would like to put this into the 7 segment display
        // Address each 7 segent unit, one after the other; left to right
// Code cut (but it should be == not =)
        Disable_Interrupts;
        TM1637DisplayAll(uint8_t num, uint8_t pos);
        Enable_Interrupts;

Code isn't being executed because gotos never return to the call, they just carry on from the label.  Try this instead:
// TimingISR& theISR means you can change the values in theISR
// TimingISR  theISR means you copy theISR and all changes are lost when the function exits.
// TimingISR const& theISR means you can't change the values in theISR
void CancelPower (TimingISR& theISR)
{
  pinMode(PIN_RELAY, OUTPUT);
  digitalWrite(PIN_RELAY, LOW);  // turn off the heat
  DisplayAll(theISR);  //ready to accumulate 'heating' time input
  delay(3000);     //let it display for 3 Count_Seconds,
  ClearDisplay();
  theISR.lead_char = 'A';        //ready to accumulate 'heating' time input
  theISR.num_min = '0';
  theISR.tens_sec = '0';
  theISR.unit_sec = '0';
  theISR.Disable_interrupts(); // This should be a function that does something, not a bool
  theISR.Count_Seconds = 0;
}

I'm afraid that's just some of the things you need to change, BUT that's one hell of a program for a first attempts and that's the only reason I raised so many issues.  Try again and post it again, I'd love to  see the differences.


text:
Playing WAV file from Arduino Uno using Ethernet R3 Shield
I'm trying to start a project where I have a 6 sec recording (wav file: 8 bit, 8 or 16 kHz, mono) on a micro-SD card and want to play it through my Arduino Uno on an 8 Ohm, 0.1 W speaker. I've looked at many different forums and threads for how to do this. One that continually comes up is this link, but this is for the Due and I can't figure out how to adapt for the Uno.
The important bit is I am using an Ethernet R3 shield which has a built in micro-SD card reader. Much of the code and tutorials I found use the TMRpcm library, setting the speaker pin to 9, the SDChipSelectPin to 4, with various wire connection geometries depending on which tutorial you read. I really need help trying to figure out how the wiring is supposed to go. I, honestly, do not understand what's going on and am hoping someone will take the time and can explain this pretty pedagogically. Currently, no matter what I try, I just hear high-pitched static or fast periodic noises.

Your Arduino UNO won't play any wave file the way you're expecting. There's not enough processing power to do that.
In order to play audio using small MCUs such as AVR (or PIC for example) you must use the BTC algorithm. Please, check this out : http://www.radanpro.com/Radan2400/mikrokontroleri/How%20to%20make%20sound%20with%20a%20PIC%20chip.htm
and download the software which can convert your wave file into an array which can be then played by Arduino using a BTC algorithm. Schematics on how to place reistors and speakers to match impedance are provided and suggested on the software as well.

Thank you ShunShirou. I'll try out your advice and repost to let you know how it goe


text:
Arduino MKR1000 problem with only two HTTP Client Post Request
When I use MKR1000 with ARDUINOHTTPCLIENT library and some simple http post example I have problem that my Arduino sends the request only twice. After that I get error code in response -2. I have tried to change time and restart the Arduino many times, but I keep getting the same problem. I change server domain where my Arduino make call and the problem is still same.
Here is code. Can anyone help me:
#include "ArduinoHttpClient.h"
#include "WiFi101.h"

//Setup Wifi Parameters
char ssid[] = "xxxxxxxxxxxx";
char pass[] = "xxxxxxxxxxxx";
char serverAddress[] = "xxxxxx.xxxxxxx.com";
int port = 80;

WiFiClient wifi;
HttpClient client = HttpClient(wifi, serverAddress, port);
int status = WL_IDLE_STATUS;
String response;
int statusCode = 0;

void setup()
{
  Serial.begin(9600);
  while ( status != WL_CONNECTED)
  {
    Serial.print("Attempting to connect to Network named: ");
    Serial.println(ssid);

    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid, pass);
    delay(6000);
  }

  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);
}

void loop()
{
  Serial.println("making POST request");
  String contentType = "application/x-www-form-urlencoded";
  String postData = "name=Alice&age=12";

  client.post("/public/insert_mysql.php HTTP/1.1", contentType, postData);

  // read the status code and body of the response
  statusCode = client.responseStatusCode();
  response = client.responseBody();

  Serial.print("Status code: ");
  Serial.println(statusCode);
  Serial.print("Response: ");
  Serial.println(response);

  Serial.println("Wait five seconds");
  delay(5000);
}

This is information from Serial Debug:
SSID: xxxxxxxxxxxxx
IP Address: xxxxxxxxx
making POST request
Status code: 200
Response:
Wait five seconds
making POST request
Status code: 200
Response:
Wait five seconds
making POST request
Status code: -2
Response:
Wait five seconds
making POST request
Status code: -2
Response:
Wait five seconds
making POST request
Status code: -2
Response:
Wait five seconds
making POST request

I'm having the same issue...no answers. Pretty disappointed by the poor arduino examples and lack of community support


text:
Problem uploading code to Arduino Uno using stino
I am having problems uploading my code to my Arduino Uno. The code that's already up, is running normally. The error code I get is:
ioctl("TIOCMSET"): Connection timed out
avrdude: stk500_recv(): programmer is not responding
ioctl("TIOCMSET"): Connection timed out
[Stino - Error 1]