body:
I have a project which runs a continuous loop and listens for the push of a button to light an led and activate a servo motor on an Arduino Uno (R2). The arduino is powered by 4 AA batteries, and the servo is powered by a 9V. I'm wondering how long I can leave this running off battery power. Does anyone know how to estimate this? As a side note, if anyone spots a way to improve battery life in my sketch / wiring, I'd love to know.

Below is my code and attached is the wiring diagram for the project (minus the batteries).

        #include <Servo.h>

    const int buttonPin = 2;     // the number of the pushbutton pin
    boolean buttonPushed = false;

    const int ledPin =  13;      // the number of the LED pin

    const int servoPin = 9;
    Servo servo;
    int angle = 0;
    int servoStartAngle = 90;
    int servoEndAngle = 10;

    boolean servoActivated = false;

    // variables will change:
    int buttonState = 0;         // variable for reading the pushbutton status

    int photoCellPin = 2;
    int photoCellThreshold = 500;
    int photoCellActivated = false;

    void setup() {
      Serial.begin(9600);
      // initialize the LED pin as an output:
      pinMode(ledPin, OUTPUT);
      // initialize the pushbutton pin as an input:
      pinMode(buttonPin, INPUT);

      servo.attach(servoPin);
      servo.write(servoStartAngle);

    }

    void loop(){
      // read the state of the pushbutton value:
      buttonState = digitalRead(buttonPin);

      int photoCellVal = analogRead(photoCellPin);

      if (photoCellVal > photoCellThreshold){
       photoCellActivated = true;
      } else {
       photoCellActivated = false;
      }

      // check if the pushbutton is pressed.
      // if it is, the buttonState is HIGH:
      if (buttonState == LOW && buttonPushed == false) {
        // turn LED on:
        buttonPushed = true;
        Serial.println("button pushed");
      } else if (buttonState == LOW && buttonPushed == true){
       buttonPushed = false;
       Serial.println('deactivate');
      }

      if (buttonPushed == true){
       digitalWrite(ledPin, HIGH);
      } else {
       digitalWrite(ledPin, LOW);
      }

      if (buttonPushed && servoActivated == false && photoCellActivated == true){
        servoActivated = true;
        Serial.println("activate motor");

        for(angle = servoStartAngle; angle > servoEndAngle; angle--){
          servo.write(angle);
          Serial.println(angle);
          delay(15);
        }
      } else if (buttonPushed == false && servoActivated == true){ //deactivate
        for(angle = servoEndAngle; angle < servoStartAngle; angle++){
          servo.write(angle);
          Serial.println(angle);
          delay(15);
        }
        delay(200);
        servoActivated = false;

      }

      delay(200);
    }

title: estimating battery run time

Answers: 2

body:
I can support what mheavers said in a comment above. Use a Bareduino or any kind of custom Board, use sleep-modes and avoid delay(). I wrote a blog-post about my experiences with this setup [here][1], if you get it right the ATmel can go down below 1mA in sleep. In your case an extreme scenario (depending on your usage pattern) could be to wake-up the Arduino with an interrupt triggered through the sensor and otherwise sleep completely. You will find example on the net where people used a setup like this for remote controls for instance.

  [1]: https://holadimake.wordpress.com/2015/01/02/building-a-cellular-tracker-part3-running-on-batteries-for-months/

body:
>I'm wondering how long I can leave this running off battery power. Does anyone know how to estimate this?

If your circuit draws 1A @ 12V, a 12V 1Ah battery will power it for approximately one hour. A 9V alkaline typically contains about 565mAh. You can use the datasheets to sum all the power consumption, but its probably easier just to measure it with a multimeter.

> As a side note, if anyone spots a way to improve battery life in my
> sketch / wiring, I'd love to know.

-Check out the ATTiny series ([parametric][1]); they are tiny, low-power, and Arduino-compatible; perfect when you only need a couple of pins.

-Use an interrupt to monitor the button's pin; the MCU can sleep until the interrupt fires.

Generally:
1) The interrupt will set a flag so main() knows that something happened, then wake the processor.
2) Main() resumes, checks the flag, turns on/off the LED accordingly, tells the servo where to go, waits for the servo to get there (delay()), clears the flag, and then puts the MCU back to sleep.

-As others have pointed out, delay() is bad. delay() tells the MCU to **do nothing** (NO-OP) repeatedly, for a period of time. This is different from having **nothing to do** because it's asleep.

  [1]: http://www.atmel.com/v2PFResults.aspx#(actives:!(8238,8394,8362,8282,8431,8300,8358,8392,8378,8445,8236,8449,8474,8248,8264,8447,8256,8254,8286,8462,8429,8458,8466,8400,8302,8278),data:(area:'',category:'34864[33180[33086]]',pm:!((i:8238,v:!(1,7)),(i:8394,v:!(0,7)),(i:8362,v:!(5,12)),(i:8282,v:!(5)),(i:8431,v:!(1,8)),(i:8300,v:!(1,5)),(i:8358,v:!(1,19)),(i:8392,v:!(0,1)),(i:8378,v:!n),(i:8445,v:!(5,6,9)),(i:8236,v:!(0,9)),(i:8449,v:!(1,3)),(i:8474,v:!(0)),(i:8248,v:!(0,1)),(i:8264,v:!(1,2)),(i:8447,v:!(0,1)),(i:8256,v:!(1,4)),(i:8254,v:!(3,16)),(i:8286,v:!(0)),(i:8462,v:!(0,2)),(i:8429,v:!(1,2)),(i:8458,v:!(0,1)),(i:8466,v:!(4)),(i:8400,v:!(0,7)),(i:8302,v:!(0)),(i:8278,v:!(0))),view:table),sc:1)


body:
I am developing a product, and to ease my job i am planning to use MCU inside the arduino with the library of Arduino.

Since all the registers are already defined inside the library, and all required things to registers of corresponding MCU are done to "make a pin input/output , enable interrupt , enable UART , enable I2C". I think that i can directly use the arduino coding enviroment even if i use MCU seperately.

Is it possible and how?  (can i use it in commertial product, i have already prototyped it with arduino)

title: Can i use arduino code, without using arduino board but just using MCU included

Answers: 3

body: Yes, you can. Once you have a .hex file for a specific MCU and environment you can use a programmer to upload it to a discrete MCU.

body:
Ignacio said everything is needed. Just search on google :) You can use programmer like [khazama][1].

Also you can use arduino board to program atmel chips.
[Using an Arduino as an AVR ISP ][2]

And now you need only .hex file to upload to your chip

[How to find .HEX][3]

I just want to point out one thing. Do not play with lock bits:)

  [1]: http://khazama.com/project/programmer/
  [2]: http://arduino.cc/en/Tutorial/ArduinoISP
  [3]: https://alselectro.wordpress.com/2014/01/26/where-are-the-hex-files-compiled-by-arduino/

body:
You can program an AVR microcontroller easily with an existing Arduino as the programmer. AFAIK there's no easy way around SMD packages. The last time I've gotten them, I have to solder programming wires on them before placing it on the board. If you have space, you can also wire the ISP pins to a connector on the board.

In any case, here are the steps to program your chip, whether DIP or SMD.

1. Upload the Arduino ISP Sketch to your Arduino board's MCU.
2. Wire up the Vcc and GND, and the SPI pins (MOSI,MISO,SCL). (The wiring is actually described in the comment section of the sketch. As for the pin out on the ATmega328, go to [page 3][1]. You can find similar datasheets if you're using other MCUs.)
3. Write your code
4. Click "File>Upload using programmer" or just press Ctrl + Shift + U.
5. Done!

I think most AVR MCUs come with an internal calibrated resonator, but if you want to drive it at a higher speed (16MHz/20MHz...) you will need to connect the MCU to a crystal oscillator. As always, refer to the datasheet. ;-)

Here's another link you can refer to: [link][2]

Hope this helps.

  [1]: http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf
  [2]: http://arduino.cc/en/Tutorial/ArduinoToBreadboard


body:
I'm intending to set up a digital delay using a circular buffer (in SRAM) with an Arduino Due (@84MHz). The lenth of the buffer determines the delay. I need about 1us resolution and the delay needs to be dynamically settable between 0 - 500us. I'll probably use most of the memory just for the buffer.

I've got a very basic setup going (with a fixed delay, no buffer), that just updates a temporary variable with the current state of the input signal and then writes the whole word to another port in order to set the state.

Next up is designing the buffer so I can add some delay to the output of the signal.

Filling the buffer using interrupts watching signals on the same port shouldn't be too difficult but I am wondering:

a) taking speed in consideration, which buffer method will have the least processing overhead? Memory stack or an array[], or someting else?

b) is there a way to read a port and set an output port in one clock cycle? I am now using `REG_PIOD_ODSR=outbyte;` but ideally it needs to point to a memory address directly.

title: fast memory buffer and setting output state

Answers: 1

body:
I would use an array, they're about as simple as it gets. 84 clock cycles per sample is very tight, but definitely possible. I'm guessing that's too close to the line to do any sort time testing - you will probably have to set up your loop to take exactly 84 instructions. This means you will probably need to hand-code in assembler. Be very mindful of branching instructions - both branches will need to take the same number of clock cycles.

The Uno (AtMega328) runs most (all?) instructions in one clock cycle, I don't know if the same applies to the Due. You would need to hand-code the assembler, check out how many cycles each instruction takes, and pad it out (there is a do nothing "NOP" instruction, which typically takes one cycle.

HOWEVER -

You can get all this work done for you by using a chip made for this purpose. This is called a Digital Delay Line, http://en.wikipedia.org/wiki/Digital_delay_line (or Analog Delay Line if you want analog values, e.g. for sound playback).


body:
so I'm using a promini running on solar power. For some reason, after sometime it gets stuck with the green led flashing and only by cutting power can I reset the promini. Even the reset button doesnt work. Exactly like in this post "https://arduino.stackexchange.com/questions/2922/watchdog-timer-stuck-in-restart-loop-green-led-flashing". However, the strange thing is that I am not even using a watchdog timer. So what could be the cause of it? Could it be due to the lack of power from my solar panel?

Here is my code

    #include <SPI.h>
    #include <RF24.h>

    int green = 8;
    int red = 6;

    // ce,csn pins
    RF24 radio(9,10);

    // init data buffer to hold a sensor type byte and one uint16_t sensor data
    unsigned char data[3] = {
      0};
    unsigned long count=0;

    void(* resetFunc) (void) = 0;//declare reset function at address 0
    void setup(void)
    {
      pinMode(4, OUTPUT);
      digitalWrite(4,HIGH);
      pinMode(5, OUTPUT);
      pinMode(green, OUTPUT);
      pinMode(red, OUTPUT);
      pinMode(3, OUTPUT);

      Serial.begin(57600);
      Serial.println("**************V1 Send Sensor Data***********");
      radio.begin();
      radio.setPALevel(RF24_PA_MAX);
      radio.setChannel(0x4c);

      // open pipe for writing
      radio.openWritingPipe(0xF0F0F0F0E1LL);

      radio.enableDynamicPayloads();
      radio.setAutoAck(false);
        radio.setDataRate(RF24_1MBPS);
      radio.powerUp();
      Serial.println("...Sending");

    }

    void loop(void)
    {
      digitalWrite(5,HIGH);
      delay(50);
      uint16_t sensorValue = analogRead(0);
      digitalWrite(5,LOW);

      Serial.println(sensorValue);
      if (sensorValue > 600){
        digitalWrite(red,LOW );
        digitalWrite(green,HIGH);
      }
      if (sensorValue >= 0 && sensorValue <= 300){
        digitalWrite(red,HIGH);
        digitalWrite(green,LOW);
      }

      //assign identification to the node.
      // In use = A & B;
      data[0] = 'B';
      //do the bit shift to put uint16 into uint8 array
      data[1] = sensorValue >> 8;
      data[2] = sensorValue;
      Serial.print(count);
      Serial.print("   |   Identity: ");
      Serial.print(data[0]);
      Serial.print("   |   ");
      Serial.print(" data[1]: ");
      Serial.print(data[1]);
      Serial.print("  |  data[2]: ");
      Serial.print(data[2]);
      digitalWrite(3,HIGH);
      // print and increment the counter
      radio.startWrite(data, sizeof(uint16_t)+1);
      Serial.print("  | Temperature sent:  ");
      Serial.println(sensorValue);
      digitalWrite(3,LOW);
      // pause 5 seconds
      delay(5000);
      resetFunc();  //call reset
    }

Thank you so much!

title: Arduino ProMini green led flashing and unable to reset

Answers: 0


body:
I'm working on data acquisition from a sensor attached to the Arduino : MPU6050 using a model in Ssimulink. I have installed the hardware support in Simulink but I don't know how to start building the model. The model must read the data from the Arduino by deploying it into the Arduino.

My connection Arduino <=> MPU6050 is :

    Arduino    MPU 9150
    3.3V       VCC
    GND        GND
    A5         SCL
    A4         SDA
    DIGITAL 2  INT
    GND        AD0

update : i have use a s-function but I get the following error:
_The call to realtime_make_rtw_hook, during the after_make hook generated the following error: Could not download the model to the target hardware. Verify the connection between the computer and target hardware.

The build process will terminate as a result.

Caused by: Could not download the model to the target hardware. Verify the connection between the computer and target hardware._

But the target is definitely connected, and downloading others module (like led blinking ) with simulink is working fine. I've also tested this on a different PC with Windows 8 (64bits) with the same result. Can anyone give me a hint please?

title: Simulink with arduino : data acquisition

Answers: 1

body:
I just made my GY-521(MPU6050) work with Simulink using s-function.
I wish this would be helpful for you.

I am using an Arduino MEGA 2650 board. The sensor data is read in in real time.
Note that currently only Arduino MEGA 2650, Arduino MEGA 2650 ADK, and Arduino DUE support the real time windows target.
If you are using other types of board, this answer may not applied.

Your hardware connection looks correct. But if you have some troubles you can refer to mine for checking:

    5v VCC
    GND GND
    SCL SCL(check the register map of your board)
    SDA SDA(check the register map of your board)

Above four connections are adequate if you just read raw sensor data.
INT is needed if you are going to read fused data. But I did not try that.

Next you may write a small program in Arduino IDE to ensure everything works.
You can refer to the Arduino MPU6050 examples.
The code written here will be used to construct your Simulink s-function later.

Now you can start to build your Simulink block using s-function builder.
If you did not do this before, here is a good tutorial:

https://m.youtube.com/watch?v=_OLctOFjjYQ

In our case, you need to copy Wire.h, twi.h and their .c counterparts in your current working directory where your s-function resides.

And do not forget to rename generated .c file to .cpp, and add external "C" declaration. All of these are illustrated in above video tutorial.

After all of above are done, you turn your simulation mode to external, and run.
You can view your sensor data in scope if everything goes right.

----------------

Source code and configuration used in my function:
I include all headers in the `Libraries` panel of S-Function Builder,

    #ifndef MATLAB_MEX_FILE
    #define ARDUINO 100
    #include <Arduino.h>
    #include <Wire.h>
    #include <Wire.cpp>
    #include <twi.h>
    #include <twi.c>
    #define MPU 0x68
    #endif

Wire.* and twi.* files are copied from Arduino IDE's directory. I put these files along with my S-Function block file.

The address of I2C is 0x68 here.

Next, the code for sensor outputs are placed in `Outputs` panel. And do not forget to add ports in `Data Properties` panel.

    #ifndef MATLAB_MEX_FILE
    Wire.beginTransmission(MPU);
    Wire.write(0x3B);
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 14, true);

    int raw = Wire.read() << 8;
    raw = raw | Wire.read();
    ax[0] = (float)raw / 8192.0f;

    raw = Wire.read() << 8;
    raw = raw | Wire.read();
    ay[0] = (float)raw / 8192.0f;

    raw = Wire.read() << 8;
    raw = raw | Wire.read();
    az[0] = (float)raw / 8192.0f;

    raw = Wire.read() << 8;
    raw = raw | Wire.read();
    temp[0] = (float)raw / 340.0f + 36.53f;

    raw = Wire.read() << 8;
    raw = raw | Wire.read();
    gx[0] = (float)raw / 131.0f;

    raw = Wire.read() << 8;
    raw = raw | Wire.read();
    gy[0] = (float)raw / 131.0f;

    raw = Wire.read() << 8;
    raw = raw | Wire.read();
    gz[0] = (float)raw / 131.0f;
    #endif

Finally, initialization and configuration are done in `Discrete Update` panel.

    #ifndef MATLAB_MEX_FILE
    if (xD[0] != 1) {
        Wire.begin();

        /* Do not sleep */
        Wire.beginTransmission(MPU);
        Wire.write(0x6B);
        Wire.write(0);
        Wire.endTransmission(true);

        /* Gyroscope full scale range: 250 degs/s */
        Wire.beginTransmission(MPU);
        Wire.write(0x1B);
        Wire.write(0);
        Wire.endTransmission(true);

        /* Accelerometer full scale range: 4g */
        Wire.beginTransmission(MPU);
        Wire.write(0x1C);
        Wire.write(8);
        Wire.endTransmission(true);

        xD[0] = 1;
    }
    #endif

Please refer to your board's datasheet for specific address and LSB scales. I am using GY-521 here.


body:
I want my Attiny85 to communicate with another attiny85.
one attiny should send a message to my other attiny. When he receives the correct message he should turn one led on. Just a very simple test scatch.
I don't know why but the led never turns on.

Here is my code:

1st attiny85:

    int clk_pin = 4,
        data_pin = 3,
        led = 0;

    void setup() {
      pinMode(clk_pin, INPUT);
      pinMode(data_pin, INPUT);
      pinMode(led, OUTPUT);
    }

    void loop() {
      byte incoming = shiftIn(data_pin, clk_pin, LSBFIRST);

      if (incoming == 2)
      {
        digitalWrite(led, HIGH);
        delay(1000);
        digitalWrite(led, LOW);
        delay(1000);
      }
    }

2nd attiny:

    int clk_pin = 0,
        data_pin = 1;

    void setup(){
      pinMode(clk_pin, OUTPUT);
      pinMode(data_pin, OUTPUT);
    }

    void loop(){
      byte test = 2;
      shiftOut(data_pin, clk_pin, LSBFIRST, test);

      delay(5000);
    }

I think there might be something wrong with my shiftIn/shiftOut command. It's actually the first time I'm using this.

Thanks for helping!

title: use shiftIn and shiftOut with attiny85

Answers: 1

body:
`shiftIn()` and `shiftOut()` are designed for communicating with different types of shift registers. These are typically external components which don't run code themselves, such as the 74HC595.

You can't use `shiftIn()` to read data that's been written using `shiftOut()`. The reason is that both functions try to act as the host in the communication -- i.e. the one that controls the clock line.

When you call `shiftIn()`, the clock line is pulsed each time it's ready to read a bit (i.e. it tells the shift register when to write). When you call `shiftOut()`, the clock line is pulsed each time it writes a bit (i.e. it tells the shift register when to read).

Neither one will respond to a clock line provided externally. The result is that your ATTiny's aren't synchronised so they won't be reading/writing at the same time.

A much simpler approach would be to setup a conventional serial connection between the two microcontrollers. You could do that either using [software][1] or [hardware][2] serial. The only caveat is that the sender would need to ensure the receiver is up-and-running before it transmits anything. This could be done using some kind of handshake at startup -- one device repeatedly sends something until the other replies.

  [1]: http://arduino.cc/en/Reference/SoftwareSerial
  [2]: http://arduino.cc/en/Reference/Serial


body:
I am currently doing the project in pulse measurement using an [Arduino Yún][1]. I am using the pulse sensor SEN-11574.

When I verify the code I get this error:

    Arduino: 1.5.8 (Linux), Board: "Arduino Yún"

    pulse-sensor-arduino/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
    /home/system1/Arduino/libraries/pulse-sensor-arduino/pulse-sensor-arduino.cpp:39: multiple definition of `pulsePin'
    sketch_feb10a.cpp.o:/home/system1/Downloads/arduino-1.5.8/sketch_feb10a.ino:18: first defined here
    pulse-sensor-arduino/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
    /home/system1/Arduino/libraries/pulse-sensor-arduino/pulse-sensor-arduino.cpp:39: multiple definition of `Pulse'
    sketch_feb10a.cpp.o:/home/system1/Downloads/arduino-1.5.8/sketch_feb10a.ino:18: first defined here
    collect2: error: ld returned 1 exit status
    Error compiling.

This is my code:

    #include <pulse-sensor-arduino.h>

    int pulsePin = 0;
    int blinkPin = 13;
    int fadePin = 5;
    int fadeRate = 0;

    volatile int BPM;
    volatile int Signal;
    volatile int IBI = 600;
    volatile boolean Pulse = false;
    volatile boolean QS = false;

    void setup() {

        pinMode(blinkPin, OUTPUT);
        pinMode(fadePin, OUTPUT);
        Serial.begin(115200);
    }

    void loop() {

        sendDataToProcessing('S', Signal);
        if (QS == true) {
            fadeRate = 255;
            sendDataToProcessing('B',BPM);
            sendDataToProcessing('Q',IBI);
            QS = false;
        }

        ledFadeToBeat();

        delay(5000);
    }

    void ledFadeToBeat() {
        fadeRate -= 15;
        fadeRate = constrain(fadeRate,0,255);
        analogWrite(fadePin,fadeRate);
    }

    void sendDataToProcessing(char symbol, int data ) {
        Serial.print(symbol);
        Serial.println(data);
    }

This is my pulse Arduino cpp file:

    #include "pulse-sensor-arduino.h"

    volatile int rate[10];                        // Array to hold last ten IBI values
    volatile unsigned long sampleCounter = 0;     // Used to determine pulse timing
    volatile unsigned long lastBeatTime = 0;      // Used to find IBI
    volatile int P =512;                          // Used to find peak in pulse wave, seeded
    volatile int T = 512;                         // Used to find trough in pulse wave, seeded
    volatile int thresh = 512;                    // Used to find instant moment of heart beat, seeded
    volatile int amp = 100;                       // Used to hold amplitude of pulse waveform, seeded
    volatile boolean firstBeat = true;            // Used to seed rate array so we startup with reasonable BPM
    volatile boolean secondBeat = false;          // Used to seed rate array so we startup with reasonable BPM
    volatile boolean Pulse = false;               // True when pulse wave is high, false when it's low
    volatile int pulsePin;

    volatile int PulseSensor::IBI = 600;          // Holds the time between beats, must be seeded!
    volatile int PulseSensor::BPM;                // Used to hold the pulse rate
    volatile int PulseSensor::Signal;             // Holds the incoming raw data
    volatile boolean PulseSensor::QS = false;     // Becomes true when Arduino finds a beat

    void PulseSensor::begin(int pPin)
    {
      pinMode(pulsePin, INPUT);
      pulsePin = pPin;

      // Initializes Timer1 to throw an interrupt every 2 ms.
      TCCR1A = 0x00;
      TCCR1B = 0x0C;  // CTC (Compare match mode) and ClockIO/256
      OCR1A = 0x7C;   // 2 ms
      TIMSK1 = 0x02;
      sei();          // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
    }

    // THIS IS THE TIMER 1 INTERRUPT SERVICE ROUTINE.
    // Timer 1 makes sure that we take a reading every 2 miliseconds
    ISR(TIMER1_COMPA_vect)
    {                         // Triggered when Timer1 counts to 124
      cli();                                      // Disable interrupts while we do this
      PulseSensor::Signal = analogRead(pulsePin); // Read the Pulse Sensor
      sampleCounter += 2;                         // Keep track of the time in ms with this variable
      int N = sampleCounter - lastBeatTime;       // Monitor the time since the last beat to avoid noise

      // Find the peak and trough of the pulse wave
      if(PulseSensor::Signal < thresh && N > (PulseSensor::IBI/5)*3){       // Avoid dichrotic noise by waiting 3/5 of last IBI
        if (PulseSensor::Signal < T){                        // T is the trough
          T = PulseSensor::Signal;                         // Keep track of lowest point in pulse wave
        }
      }

      if(PulseSensor::Signal > thresh && PulseSensor::Signal > P){          // Threshold condition helps avoid noise
        P = PulseSensor::Signal;                             // P is the peak
      }                                        // Keep track of highest point in pulse wave

      //  NOW IT'S TIME TO LOOK FOR THE HEART BEAT
      //
      // The signal surges up in value every time there is a pulse
      if (N > 250){                                   // Avoid high-frequency noise
        if ( (PulseSensor::Signal > thresh) && (Pulse == false) && (N > (PulseSensor::IBI/5)*3) )
        {
          Pulse = true;                               // Set the Pulse flag when we think there is a pulse
          PulseSensor::IBI = sampleCounter - lastBeatTime;         // Measure time between beats in mS
          lastBeatTime = sampleCounter;               // Keep track of time for next pulse

          if(secondBeat){                        // If this is the second beat, if secondBeat == TRUE
            secondBeat = false;                  // Clear secondBeat flag
            for(int i=0; i<=9; i++){             // Seed the running total to get a realisitic BPM at startup
              rate[i] = PulseSensor::IBI;
            }
          }

          if(firstBeat){                         // If it's the first time we found a beat, if firstBeat == TRUE
            firstBeat = false;                   // Clear firstBeat flag
            secondBeat = true;                   // Set the second beat flag
            sei();                               // Enable interrupts again
            return;                              // IBI value is unreliable so discard it
          }

          // Keep a running total of the last 10 IBI values
          word runningTotal = 0;                  // Clear the runningTotal variable

          for(int i=0; i<=8; i++){                // Shift data in the rate array
            rate[i] = rate[i+1];                  // And drop the oldest IBI value
            runningTotal += rate[i];              // Add up the 9 oldest IBI values
          }

          rate[9] = PulseSensor::IBI;                          // add the latest IBI to the rate array
          runningTotal += rate[9];                // Add the latest IBI to runningTotal
          runningTotal /= 10;                     // Average the last 10 IBI values
          PulseSensor::BPM = 60000/runningTotal;               // How many beats can fit into a minute? that's BPM!
          PulseSensor::QS = true;                              // Set Quantified Self flag
          // QS FLAG IS NOT CLEARED INSIDE THIS ISR
        }
      }

      if (PulseSensor::Signal < thresh && Pulse == true){   // When the values are going down, the beat is over
        Pulse = false;                         // Reset the Pulse flag so we can do it again
        amp = P - T;                           // Get amplitude of the pulse wave
        thresh = amp/2 + T;                    // Set thresh at 50% of the amplitude
        P = thresh;                            // Reset these for next time
        T = thresh;
      }

      if (N > 2500){                           // If 2.5 seconds go by without a beat
        thresh = 512;                          // Set thresh default
        P = 512;                               // Set P default
        T = 512;                               // Set T default
        lastBeatTime = sampleCounter;          // Bring the lastBeatTime up to date
        firstBeat = true;                      // Set these to avoid noise
        secondBeat = false;                    // When we get the heartbeat back
      }

      sei();                                   // Enable interrupts when youre done!
    } // end ISR

This is my pulse Arduino header file:

    #ifndef PULSE_SENSOR_ARDUINO_H
    #define PULSE_SENSOR_ARDUINO_H

    #include "Arduino.h"

    class PulseSensor
    {
    public:
      static void begin(int pulsePin);

      static volatile int BPM;
      static volatile int Signal;
      static volatile int IBI;
      static volatile boolean QS;
    };

    #endif

I modified the program, but there is a new error present:

    Arduino: 1.5.8 (Linux), Board: "Arduino Yún"

    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
    /home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `PulseSensor::begin(int)'
    pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
    /home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `pulsePin'
    pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `__vector_17':
    /home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:54: multiple definition of `__vector_17'
    pulsesensor.cpp.o:pulsesensor.cpp:54: first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
    /home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `PulseSensor::Signal'
    pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
    /home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `sampleCounter'
    pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
    /home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `lastBeatTime'
    pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o:(.data.thresh+0x0): multiple definition of `thresh'
    pulsesensor.cpp.o:(.data.thresh+0x0): first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o:(.data._ZN11PulseSensor3IBIE+0x0): multiple definition of `PulseSensor::IBI'
    pulsesensor.cpp.o:(.data._ZN11PulseSensor3IBIE+0x0): first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o:(.data.T+0x0): multiple definition of `T'
    pulsesensor.cpp.o:(.data.T+0x0): first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o:(.data.P+0x0): multiple definition of `P'
    pulsesensor.cpp.o:(.data.P+0x0): first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
    /home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `Pulse'
    pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
    /home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `rate'
    pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
    /home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `PulseSensor::BPM'
    pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
    /home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `PulseSensor::QS'
    pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o:(.data.firstBeat+0x0): multiple definition of `firstBeat'
    pulsesensor.cpp.o:(.data.firstBeat+0x0): first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
    /home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `secondBeat'
    pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o:(.data.amp+0x0): multiple definition of `amp'
    pulsesensor.cpp.o:(.data.amp+0x0): first defined here
    collect2: error: ld returned 1 exit status
    Error compiling.

Here is my change code

    #include <pulse-sensor-arduino.h>

    int blinkPin = 13;                // Pin to blink LED at each beat
    int fadePin = 5;                  // Pin to do fancy classy fading blink at each beat
    int fadeRate = 0;                 // Used to fade LED on with PWM on fadePin

    void setup(){
      pinMode(blinkPin,OUTPUT);         // Pin that will blink to your heartbeat!
      pinMode(fadePin,OUTPUT);          // Pin that will fade to your heartbeat!
      Serial.begin(115200);             // We agree to talk fast!

    }

    void loop(){
      sendDataToProcessing('P', PulseSensor::Signal);     // Send Processing the raw Pulse Sensor data
      if (PulseSensor::QS == true){                       // Quantified Self flag is true when arduino finds a heartbeat
        fadeRate = 255;                  // Set 'fadeRate' Variable to 255 to fade LED with pulse
        sendDataToProcessing('B',PulseSensor::BPM);   // Send heart rate with a 'B' prefix
        sendDataToProcessing('Q',PulseSensor::IBI);   // Send time between beats with a 'Q' prefix
        PulseSensor::QS = false;                      // Reset the Quantified Self flag for next time
      }

      ledFadeToBeat();

      delay(5000);                             //  Take a break
    }

    void ledFadeToBeat(){
      fadeRate -= 15;                         //  Set LED fade value
      fadeRate = constrain(fadeRate,0,255);   //  Keep LED fade value from going into negative numbers!
      analogWrite(fadePin,fadeRate);          //  Fade LED
    }

    void sendDataToProcessing(char symbol, int data ){
        Serial.print(symbol);                // Symbol prefix tells Processing what type of data is coming
        Serial.println(data);                // The data to send culminating in a carriage return
    }

My cpp file:

    #include "pulse-sensor-arduino.h"

    volatile int rate[10];                        // Array to hold last ten IBI values
    volatile unsigned long sampleCounter = 0;     // Used to determine pulse timing
    volatile unsigned long lastBeatTime = 0;      // Used to find IBI
    volatile int P =512;                          // Used to find peak in pulse wave, seeded
    volatile int T = 512;                         // Used to find trough in pulse wave, seeded
    volatile int thresh = 512;                    // Used to find instant moment of heart beat, seeded
    volatile int amp = 100;                       // Used to hold amplitude of pulse waveform, seeded
    volatile boolean firstBeat = true;            // Used to seed rate array so we startup with reasonable BPM
    volatile boolean secondBeat = false;          // Used to seed rate array so we startup with reasonable BPM
    volatile boolean Pulse = false;               // True when pulse wave is high, false when it's low
    volatile int pulsePin;

    volatile int PulseSensor::IBI = 600;          // Holds the time between beats, must be seeded!
    volatile int PulseSensor::BPM;                // Used to hold the pulse rate
    volatile int PulseSensor::Signal;             // Holds the incoming raw data
    volatile boolean PulseSensor::QS = false;     // Becomes true when Arduino finds a beat

    void PulseSensor::begin(int pPin)
    {
      pinMode(pulsePin, INPUT);
      pulsePin = pPin;

      // Initializes Timer1 to throw an interrupt every 2 ms.
      TCCR1A = 0x00;
      TCCR1B = 0x0C;  // CTC (Compare match mode) and ClockIO/256
      OCR1A = 0x7C;   // 2 ms
      TIMSK1 = 0x02;
      sei();          // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
    }

    // THIS IS THE TIMER 1 INTERRUPT SERVICE ROUTINE.
    // Timer 1 makes sure that we take a reading every 2 miliseconds
    ISR(TIMER1_COMPA_vect)
    {                         // Triggered when Timer1 counts to 124
      cli();                                      // Disable interrupts while we do this
      PulseSensor::Signal = analogRead(pulsePin);              // read the Pulse Sensor
      sampleCounter += 2;                         // Keep track of the time in ms with this variable
      int N = sampleCounter - lastBeatTime;       // Monitor the time since the last beat to avoid noise

      //  Find the peak and trough of the pulse wave
      if(PulseSensor::Signal < thresh && N > (PulseSensor::IBI/5)*3){       // Avoid dichrotic noise by waiting 3/5 of last IBI
        if (PulseSensor::Signal < T){                        // T is the trough
          T = PulseSensor::Signal;                         // Keep track of lowest point in pulse wave
        }
      }

      if(PulseSensor::Signal > thresh && PulseSensor::Signal > P){          // Threshold condition helps avoid noise
        P = PulseSensor::Signal;                             // P is the peak
      }                                        // Keep track of highest point in pulse wave

      //  NOW IT'S TIME TO LOOK FOR THE HEART BEAT
      // signal surges up in value every time there is a pulse
      if (N > 250){                                   // Avoid high frequency noise
        if ( (PulseSensor::Signal > thresh) && (Pulse == false) && (N > (PulseSensor::IBI/5)*3) )
        {
          Pulse = true;                               // Set the Pulse flag when we think there is a pulse
          PulseSensor::IBI = sampleCounter - lastBeatTime;         // measure time between beats in mS
          lastBeatTime = sampleCounter;               // Keep track of time for next pulse

          if(secondBeat){                        // If this is the second beat, if secondBeat == TRUE
            secondBeat = false;                  // Clear secondBeat flag
            for(int i=0; i<=9; i++){             // Seed the running total to get a realisitic BPM at startup
              rate[i] = PulseSensor::IBI;
            }
          }

          if(firstBeat){                         // If it's the first time we found a beat, if firstBeat == TRUE
            firstBeat = false;                   // Clear firstBeat flag
            secondBeat = true;                   // Set the second beat flag
            sei();                               // Enable interrupts again
            return;                              // IBI value is unreliable so discard it
          }

          // Keep a running total of the last 10 IBI values
          word runningTotal = 0;                  // Clear the runningTotal variable

          for(int i=0; i<=8; i++){                // Shift data in the rate array
            rate[i] = rate[i+1];                  // And drop the oldest IBI value
            runningTotal += rate[i];              // Add up the 9 oldest IBI values
          }

          rate[9] = PulseSensor::IBI;                          // Add the latest IBI to the rate array
          runningTotal += rate[9];                // Add the latest IBI to runningTotal
          runningTotal /= 10;                     // Average the last 10 IBI values
          PulseSensor::BPM = 60000/runningTotal;               // How many beats can fit into a minute? that's BPM!
          PulseSensor::QS = true;                              // Set Quantified Self flag
          // QS FLAG IS NOT CLEARED INSIDE THIS ISR
        }
      }

      if (PulseSensor::Signal < thresh && Pulse == true){   // When the values are going down, the beat is over
        Pulse = false;                         // Reset the Pulse flag so we can do it again
        amp = P - T;                           // Get amplitude of the pulse wave
        thresh = amp/2 + T;                    // Set thresh at 50% of the amplitude
        P = thresh;                            // Reset these for next time
        T = thresh;
      }

      if (N > 2500){                           // If 2.5 seconds go by without a beat
        thresh = 512;                          // Set thresh default
        P = 512;                               // Set P default
        T = 512;                               // Set T default
        lastBeatTime = sampleCounter;          // Bring the lastBeatTime up to date
        firstBeat = true;                      // Set these to avoid noise
        secondBeat = false;                    // When we get the heartbeat back
      }

      sei();                                   // Enable interrupts when youre done!
    } // end ISR

  [1]: https://www.arduino.cc/en/Main/ArduinoBoardYun

title: Pulse measurement

Answers: 1

body:
(1)The declaration

     volatile boolean Pulse = false;

occurs in two locations.

Is that intended?

(2) Also

    volatile int PulseSensor::BPM;                // used to hold the pulse rate
    volatile int PulseSensor::IBI = 600;          // holds the time between beats, must be seeded!
    volatile int PulseSensor::Signal;             // holds the incoming raw data


body:
I have a arduino program that I wrote with my teammembers. We are working on a project and try to move a RC car. Here is our code.

    int forward =12 ; //assign to correlating pin attached to TP06
    int backward = 11; //assign to correlating pin attached to TP07
    int left = 10; //assign to correlating pin attached to (left steer)
    int right = 9; //assign to correlating pin attached to (right steer)

    // TP09 & TP02 (don't remember which is left and right)

    void setup() {
    pinMode(forward, OUTPUT);
    pinMode(backward, OUTPUT);
    pinMode(left, OUTPUT);
    pinMode(right, OUTPUT);
    }

    void move_Forward() {
    digitalWrite(forward, HIGH);
    digitalWrite(backward, LOW);
    }

    void move_Backward() {
    digitalWrite(backward, HIGH);
    digitalWrite(forward, LOW);
    }

    void turn_Left() {
    digitalWrite(left, HIGH);
    digitalWrite(right, LOW);
    }

    void turn_Right() {
    digitalWrite(right, HIGH);
    digitalWrite(left, LOW);
    }

    void stop_Completely() {
    digitalWrite(forward, LOW);
    digitalWrite(backward, LOW);
    digitalWrite(right, LOW);
    digitalWrite(left, LOW);
    }

    // loop will keep going while arduino has power
    void loop() {
    move_Forward();
    turn_Left();
    }

When we run this code, for some reason forward pin and left pins are becoming deactivated, which are the pin numbers 12 and 10. Like it does not supply voltage anymore for some reason. However right pin and backward pins, which are pins 9 and 11, which was not included in loop, works! I can run the RC car with these pins. I dont understand why this is the case. Shouldn't the left and forward pins work? If they are not working, how come? Sorry I am new to arduino programming language and its been very challenging for me and my group. Thanks in advance.

title: Arduino program wont work properly for some reason

Answers: 3

body:
On many Arduinos, those pins (10-12) are shared with the ICSP header - are you programming/testing with it plugged in or unplugged? If plugged in, you might be affected by what you're plugged into.

Here's a useful pinout: http://t.co/MKtmCILSdj

Here's a Nano pinout: ![Nano pinout][1]

  [1]: https://i.stack.imgur.com/yykxv.png

Note that the ICSP is electrically connected to pins D11, D12 and D13 - so if you have something plugged into the ICSP header, you have something connected to those pins which might be causing your problem.

If you're programming via serial port (TX/RX) and have nothing connected to ICSP, then this isn't your issue. If that's a case, it's possible to fry a few pins on a Nano and have it still appear to mostly work - trying another couple of pins might tell you more. (For instance, try D4 and D5 instead of D10 and D12.)

body: Have you tested this on more than one Arduino? My first Arduino board had a dead UART. Took me weeks and purchasing a second Arduino to figure it out. It worked well enough to not initially suspect the UART (I'm not a complete idiot). ;)

body:
First: turn off the old direction before turning on the new one. Now you're doing it the other way around.

Then, in your main loop you're repeating forward and left over and over. I guess you want to move forward for some time, then turn left, then move forward again, etc.
But moving forward does deactivate the reverse, but doesn't change left or right. So you're always repeating commands which haven't been changed in the first place: forward will always be active, and so will left be. You'll go in a circle, I don't know if that is the idea.

If you want to go straight, you'll probably want to turn off both left and right? Then add a delay before turning; right now your commands occur within microseconds of each other.


body:
<!-- language-all: lang-cpp -->

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12,11,5,4,3,2);
    int visitor=0;  //variable for counting visitor number

    unsigned long timer_1,timer_2;  //variables for recording time for ir_1 and ir_2

    void setup() {
       lcd.begin(20,4);
       pinMode(A0,INPUT);
       pinMode(A1,INPUT);
    }

    void loop(){
     lcd.setCursor(0,4);
       lcd.print("visitor=");
       lcd.setCursor(8, 4);

       lcd.print(visitor);

       if(digitalRead(A0)==1 && digitalRead(A1)==0)
      {
        timer_1= millis();
      }
      if(digitalRead(A0)==0 && digitalRead(A1)==1)
      {
        timer_2= millis();
      }
      if(timer_1>timer_2)
      {
       lcd.setCursor(8,4);
       visitor=visitor+1;
       lcd.print(visitor);
       delay(2000);
       timer_1=0;
       timer_2=0;
      }
     else if(timer_1<timer_2)
      {
       lcd.setCursor(8,4);
       visitor=visitor-1;
        if (visitor<=0)
      {
        visitor=0;
      }
       lcd.print(visitor);
       delay(2000);
       timer_1=0;
       timer_2=0;

      }

    }

Two IR sensors are placed in A0 and A1.

While the value of `visitor` is decreasing from 10 to 9 the LCD is showing 90 because  the '0' of previous 10 is here. How can I remove it?

title: Value of the counter collide on my lcd while decreasing. How can I remove it?

Answers: 1

body:
A simple option would be to call `lcd.clear()` at the start of `loop()`. That will clear the entire LCD display. Everything else should work fine because it looks like you're outputting the entire display contents every time round.

Alternatively, you could remove the extra digit by printing a space over it, e.g.:

    if (visitor < 10) print(" ");
    lcd.print(visitor);

If `visitor` is a 1-digit number (i.e. less than 10), it will output a space at the start, getting rid of any underlying digits leftover from a previous iteration. If you want the number to be left-aligned then you could print the space after the number instead.


body:
I need to create a interruption-proof power for a project of mine, very similar to the design [of this link][1].

My problem is that I need to adjust the current delivered of the solar panel (21V, 1.2A) to 5V and simultaneously charge a battery 12V, 18Ah. If the solar panel does not supply power, the battery takes its place.

Does anyone know any circuit to do something? Or can someone give me a light as do something?

  [1]: http://www.feirinhadigital.com.br/rbr/ham/projetos-usuarios/NO-BREAK/nobreak.htm

title: create a interruption-proof power

Answers: 1

body:
Rough block diagrams below show two ways this can be achieved - "Easiest" costs least but is inefficient. "Better" uses PV panel output more efficiently. Details of either can be discussed if of interest.

'Schottky diodes' should be used to minimise losses.

(1) "Easiest"

Connect PV panel to battery with diode.
Panel is clamped to battery voltage (+ diode drop).
This will not hurt the PV panel but wastes some of the available power.
[What is the formal PV panel specification. Is it 21V O/C or loaded or .... Do you have a datasheet link for it?].

Use 12V (nominal) to 5V converter to power load.
This could be

 - A linear regulator - only about 40% efficient - very wasteful.

 - A buck converter (build or buy from eg ebay)

![enter image description here][1]

(2) "Better"

Use a buck regulator to charge the battery - ideally an MPPT (maximum power point transfer) controller. Details can be discussed if you are interested.

Use a second buck regulator to power the load. This must be capable of (at least) 11V to 22V input. Power this from a Schottky diode from the PV panel AND a Schottky diode from the battery. When the panel voltage is > battery voltage the panel will power the load.

![enter image description here][2]

  [1]: https://i.stack.imgur.com/8Vxlt.jpg
  [2]: https://i.stack.imgur.com/T4GsC.jpg


body:
I am trying to measure a users 'hand steadiness' in order to control a video game character in UNITY3D. I am using a MinIMU-9 Gyro/Accelerometer/Compass linked with Arduino. I can measure pitch/roll etc in Arduino...and I have passed previous Arduino measurements into Unity via the serial command but I am l trying to do two things:
1. simplify & reduce noise in the data coming from the magnetometer reading before I pass it into Unity by taking an average of every 10 magnetometer readings.
2. Combining the three magnetometer values to get one overall variable or measurement that can be passed into unity.

This is the demo Sketch I have but I'm not sure how to script the addition of the x,y,z magnetometer values:

<!-- language-all: lang-cpp -->

    #include <Wire.h>
    #include <LSM303.h>
    LSM303 compass;
    char report[80];
    void setup()
    {
      Serial.begin(9600);
      Wire.begin();
      compass.init();
      compass.enableDefault();
    }
    void loop()
    {
      compass.read();
      snprintf(report, sizeof(report), "A: m m m    M: m m m",
        compass.a.x, compass.a.y, compass.a.z,
        compass.m.x, compass.m.y, compass.m.z);
      Serial.println(report);
      delay(100);
    }

This is the type of 'averaging script' I would like to add in somewhere but I'm not sure where exactly to place it:

    for(int i = 0; i < 10; i++){    //take ten readings in ~0.02 seconds
        reading[i] = compass.m.y;
        delay(2);
      }
      for(int i = 0; i < 10; i++){   //average the ten readings
        finalMagYreading += reading[i];
      }
       finalMagYreading
     /= 10;

Any help with this would be great.

title: Combining & averaging magnetometer values

Answers: 0


body: I want to make a universal remote.I have an ir receiver and transmiter. I.I can use it to control my tv and other equipment.I want to also control my dish network in the US. I checked and think that the dish uses 395mhz but i am not sure.**How can i replicate a dish remote radio signal**.I know it is radio signal and not ir. **What part do I need for the arduino?**

title: I want to know how to record and play radio waves?

Answers: 1

body:
This is only a partial answer, but should be enough to get you started.

The parts are:

 1. Build a receiver http://www.somerset.net/arm/fm_only_lowtech.html
 2. Tune it to the right frequency
 3. Use it to detect the codes sent from your remote
 4. Build a transmitter http://makezine.com/projects/super-simple-fm-transmitter/
 5. Tune it to the right frequency
 6. Transmit the codes
 7. Success!

Step 3 is probably best done with a scope - you should find someone who has one, who can operate it, because they can be damaged.


body:
    // Tells the Arduino to read A2 and stores the value in “Vin”
    Vin = analogRead (tempSensor);

    // Converts the voltage value to temperature and stores it into the “TC” variable (in °C)
    TC = 500.0 * (Vin / 1024.0);

The temperature shown is about 50.25°C, sometimes it is showing 36-38°C   degrees, but the actual temperature is about 25-26°C.

Why this is happening?

Code:

    Vin = analogRead (tempSensor);
    TC=(500.0*Vin)/1023.0;
    TF = ((9.0*TC)/5.0)+32.0;
    lcd.setCursor(0, 1);
    lcd.print(TF);
    lcd.print((char)223);
    lcd.print("F ");
    lcd.print (TC);
    lcd.print((char)223);
    lcd.print("C");
    delay(1000);

title: Temperature sensor reading is higher than the actual temperature

Answers: 4

body:
It sounds like your voltage to temperature calculation is wrong. Assuming the temperature voltage relationship is linear you can work out the formula. Take two measurements at two known temperatures (quite far apart, perhaps outdoors and in) and note down the value Arduino measures for Vin. Lets call these VinA & VinB for TempA and TempB.

You can calculate measures per degree with...

MeasuresPerDeg = (TempB - TempA) /(VinB - VinA)

And the a constant as...

Constant = TempA - VinA*MeasuresPerDeg

Your equation to calculate temperature should now be

TC=MeasuresPerDeg*(Vin/1024.0) + Constant;

body:
Any chance you're printing Vin, and not TC?

500*(50.25/1024) = ~24.5

If not, please post as much of your program as possible

body:
I gave up on using a LM335, which is quite similar to your LM35. The problem is these devices self-heat due to the quiescent power they draw. The LM35 data sheet suggests you correct for this in software (footnote 5), and the LM335 datasheet dodges the bullet by quoting accuracy figures that can be achieved in an oil bath rather than free air.

But the figures you are quoting suggest you have a bigger problem, as I am talking of a few degrees inaccuracy, not tens of degrees.

I changed to a DS18B20 and never looked back - simple interface and self-heating is compensated for by the device.

body:
What are the variable types of `TC` and `TF` - int/float/double? Something else?

If they're integers, you may be losing some numerical precision in the calculation.

When you get 50.25°C - have you checked the `Vin` is correct?

Also when you write the values out, the serial.print() can take the number of decimal points as a second argument.

    // Print to three decimal places
    Serial.print("TF=");
    Serial.println((float)TF, 3);
    Serial.print("TC=");
    Serial.println((float)TC, 3);
    Serial.print("Vin=");
    Serial.println(Vin, DEC);


body:
I came across a dev board around the Atmel Xmega controller. This an AVR like used on Arduino, but with a lot of extras.

![enter image description here][1]

I was surprised to see that the board is hardly more expensive than an Arduino, despite:

> - 384kB of Flash (versus 32kB for Arduino)
- DMA
- Xmega can run at 32 MHz (16 MHz for Arduino)
- on-board OLED display
- on-board light and temperature sensors
- on-board microSD socket

For all these on-board features you'd need a shield or breakout board for Arduino. I seems to me that for a lower price than Arduino you could build a much more powerful system, which is Arduino-compatible.
How hard would it be to port Arduino to the Xmega?

see also [http://www.element14.com/community/docs/DOC-71436](http://www.element14.com/community/docs/DOC-71436)

  [1]: https://i.stack.imgur.com/UCSG3.png

title: Arduino around the Xmega?

Answers: 1

body:
There's an attempt to get the Atmel XMEGA boards working in Arduino IDE.

https://github.com/akafugu/Xmegaduino

It's not fully featured yet but appears to have to features to allow you to start hacking with this board.


body:
I am looking to buy a range finder module for an obstacle avoidance robot.
Currently, two good options based on available libraries and compatibility with Arduino and rPI are HC-SR04 and parallax ping.

In terms of form factor these seem the same. The only difference I can tell is 4 pins vs 3 pins. Also the price, with parallax being more than x4 the price. As I would rather not buy something cheaper which will need replacing, is anyone aware of further differences, that will make the parallax a better option?

both need 5V
both have max range of 3-4m
Sensor angle HC- 15 degrees, parallax cant find..

title: Choosing rangefinder for obstacle-avoiding

Answers: 1

body:
> Odds are pretty good they are real close. I've only used the sr04 with
> 4 pins (too lazy to mod) and it was ok. cant say if the parallax is
> better or not. For 4 times the price you'd expect it to be, but so far
> in robotics, price seldom reflect performance in my experience. –
> Spiked3

I've also used the SR (with 4 pins) and it worked great. <2$ on eBay


body: I am doing some computations on Matlab and I need to send those values to an Arduino Leonardo through USB serial connection. I need to send 2 variables which can vary from -400 to +400. I'm saying their values because I was able to do this with small positive values (unsigned byte), but not larger and negative numbers. Please help! Thank you

title: Matlab to Arduino communication

Answers: 2

body:
You cannot send larger values because byte only covers the range from 0-255.

To send larger values, you can break your int variable into 2 byte variables. Here's an example:

    // On Arduino
    int myVar = -123;
    byte myVar_HighByte = myVar>>8; // get the high byte
    byte myVar_LowByte = myVar; // get the low byte
    // x86 compatible machines are little-endian so we send the low byte first
    Serial.write(myVar_LowByte);
    Serial.write(myVar_HighByte);

    % On MATLAB
    s = serial('COM10')
    fopen(s)
    myVar = fread(s,1,'int16')

Disclaimer: Syntax might not be entirely correct, since I have no MATLAB or Arduino near me when I typed this. But you should get the idea. ;-)

Edit: On second thought, it might be easier to use a pointer.

    // On Arduino
    float myFloat = 3.14159265359;
    byte* ptr = (byte*) (&myFloat);
    Serial.write(*ptr++);
    Serial.write(*ptr++);
    Serial.write(*ptr++);
    Serial.write(*ptr);

    % On MATLAB
    s = serial('COM10')
    fopen(s)
    myVar = fread(s,1,'float')

Having said that, you will still have to take care of the endianness, if you use a different microcontroller.

body:
If you want to send your data directly from Matlab to the Arduino, you can try using the "Matlab Arduino Support package". It lets you read/write pins on the arduino directly from Matlab command line or script just like you would with a VERY LOW END Data Acquisition card.

This has the advantage of removing the burden of managing the serial communication. I don't know how it handles large numbers though.

http://www.mathworks.com/hardware-support/arduino-matlab.html?refresh=true


body:
I'm having a bit of a problem when sending IR Codes stored in variables. I swear I had this convered up already. I don't actually know the reason why I can't use variables in the first place. I receive data over Bluetooth Serial Com and I'm using an Arduino ProMicro as ISP for the Arduino Nano.

I want to send data over Serial comm and then send an IR code to the end receiver.

Here is some of the code():

    #include <IRremote.h> // IR Library - Encode/Decode

    void irSerial( char SerChar[] ) // Receive array of characters

    char IDChar[]={'s', 'i', 'u'}; // List of Serial Char to identify position
    String HRD[]={"Power", "Input", "ChaUp"}; // Action referece
    byte CodesIR[]={0x61A0F00F, 0x61A048B7, 0x61A050AF}; // IR Codes
    int IRArray = 2; // Size Of The array

    if ( SerChar[0] == 's' ) { // Compare Array
      for (int CountIR = 0; CountIR <= IRArray; CountIR++){ // Loop through array
        if ( SerChar[0] == IDChar[CountIR]) {
           bluetooth.println(HRD[CountIR]); // Send String in array - Works
           SendIR.sendNEC(CodesIR[CountIR],32); // Send IR in array position
        }
      }
    }
    }

There's not a problem with the current expression as it compiles normally and I can send serial data normally finishing the function. If I replace the array **CodesIR[CountIR]** for example with **0x61A0F00F** then it works perfectly.

How can I use a variable instead? Can anyone help? It is the **byte CodesIR[]** ??

I used a **Switch/Case** and it works but I prefer a variable/array and less useless coding. Thanks for understanding!

title: Send array of Infrared codes

Answers: 1

body:
Well as usual it was something stupid (-__-) I changed the **byte** array for **long** and it worked perfectly.

Here is the complete code working():

    #include <IRremote.h> // IR Library - Encode/Decode

    void irSerial( char SerChar[] ) { // Receive array of characters

        char IDChar[]={'s', 'i', 'u'}; // List of Serial Char to identify position
        String HRD[]={"Power", "Input", "ChaUp"}; // Action reference
        long CodesIR[]={0x61A0F00F, 0x61A048B7, 0x61A050AF}; // IR Codes
        int IRArray = 3; // Size Of The array # Edit

        if ( SerChar[0] == 's' ) { // Compare Array
          for (int CountIR = 0; CountIR < IRArray; CountIR++){ // Loop through array # Edit
            if ( SerChar[0] == IDChar[CountIR]) {
               Serial.println(HRD[CountIR]); // Send String in array - Works
               SendIR.sendNEC(CodesIR[CountIR],32); // Send IR in array position
            }
          }
        }
    }


body:
I am interfacing a GSM modem via Arduino at Serial port 2.

I have seen that responses fron GSM modem are subject to time. Sometime its response are fast and sometime it are slow. I  have a code like below which checks for response from GSM modem based upon a user configurable timeout value:

    sendATcommand(str_at_cmd, str_ok, 500);

    int8_t sendATcommand(char* ATcommand, char* expected_answer, unsigned int timeout)
    {
        uint8_t x=0;
        char response[100];
        unsigned long previous;
        int answer = 0;
        memset(response, '\0', 100);
        answer = 0;;
        delay(100);
        ClearSerialData(); // read and flush all data
        debug_println(ATcommand);
        Serial2.println(ATcommand);
        delay(200);
        x = 0;
        previous = millis();
        do {
           if(Serial2.available() > 0){
           response[x] = Serial2.read();
           delay(100);
           debug_print(response[x]);
           response[++x] = '\0';
           if (strstr(response, expected_answer) != NULL)
           {
               debug_print("\nAnswer Mathced");
               answer = 1;
           }
           }
        }while((answer == 0) && ((millis() - previous) < timeout));
        debug_println("\nReturning from AT Command");
        return answer;
    }

I was never able to set the correct timeout value - as at random test it failed once or twice and not received 100% success.

My question if I change the code like below

    while(Serial2.available() > 0){
       response[x] = Serial2.read();
       delay(100);
       debug_print(response[x]);
       response[++x] = '\0';
       if (strstr(response, expected_answer) != NULL)
       {
           debug_print("\nAnswer Mathced");
           answer = 1;
       }
    }

So when does Serial2.available() method returns <= 0 value. Is my above code correct - this way I overcome the timeout issue and all my GSM responses are being read - are there scenarios that I will end up in infinite loop?

title: Data at Serial Port Avaliable

Answers: 1

body:
Your code is flawed in that you are waiting a fixed time, and then hoping that the entire response will arrive quickly. Personally I would send the query, and then exit the function. Test for incoming data in your main loop, and process it when it is all received. Techniques described here: http://www.gammon.com.au/serial

The whole thing should be able to be written without delay().


body:
I'm trying to interface my Leonardo with a "Mindsensors Magic Wand" - 8 LEDs connected to a PCA8574AN chip.
On the manufacturer's page, they say it's compatible with Arduino, however no instructions or code are given.
http://www.mindsensors.com/index.php?module=pagemaster&PAGE_user_op=view_page&PAGE_id=120

I've connected the SDA, SCL, 5v, and GND connectors on the arduino to the device, but have had no luck in communicating with it. None of the LEDs light up regardless of input.

I can verify that power is being supplied.
The i2c address of the device is 0x70.
Code is below.

    #include "Wire.h"
    #define TWBR=400000L
    void setup() {
      // put your setup code here, to run once:
     Wire.begin();
    }

    void loop() {
      // put your main code here, to run repeatedly:
      delay(2000);
      Wire.beginTransmission(0x70);
      Wire.write(32);
      Wire.endTransmission();
    }

title: Interfacing Arduino Leonardo with PCA8574AN

Answers: 1

body:
**tl;dr:** It seems like you need to send a null bit (0) to terminate the communication with this board.

In the downloads section, I found a .nxc file, which I assume is a NXT code file.

In the main loop, they configure the I2C port and a "touch sensor" (I believe this is to figure out how to synchronize the text with the motor). In that, there is a main loop in which they call `DispLetter`.

This is the `DispLetter` function:

    void DispLetter (const byte & letter[])
    {
      int nbytes;
      // Wait for the end of previously sent data
      while(I2CStatus(I2Cport, nbytes)==STAT_COMM_PENDING);
      // Write buffer to send to PCF8574
      byte WriteBuf[];
      ArrayBuild(WriteBuf, I2CAddr8574, letter);
      for(int i=1; i<ArrayLen(WriteBuf); i++)
      {
         WriteBuf[i] ^= 0xff;
      }
      I2CWrite(I2Cport, 0,  WriteBuf);
    }

Let's read this code! First of all, it seems to make sure that the I2C port is connected, which we don't really have to worry about in our case since that's platform-specific.

After that, they create an array called `WriteBuf[]` that will store the data to be sent to the controller. Then we come across a function called `ArrayBuild`. Looking that up, it combines `I2CAddr8574` and `letter` and places it into the `WriteBuf` array. ([Click here for documentation for that function.][1]) Please note that the `I2CAddr8574` is just a byte containing 0x70 (the address of the chip), so we will not have to do this step since the Arduino handles the address. So, you will just have to send the `letter` array to the controller, ignoring the `WriteBuf` and `ArrayBuild`!

Let's figure out how `letter` is passed. In the main loop, they had this code:

    DispLetter(L_);
    DispLetter(E_);
    DispLetter(G_);
    DispLetter(O_);

That must display "LEGO." Let's figure out what `L_` is defined as. At the beginning of the document, they have this defined:

    // Display patterns
    // Each byte represents a column of dots
    // Bit set to 1 means lit LED.
    // Least significant bit is at top of column.
    // Last byte must be all 0
    // Maximum number of bytes par pattern: 15

    byte L_[] = {0xff, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0};
    byte E_[] = {0xff, 0x89, 0x89, 0x89, 0x89, 0x81, 0x81, 0};
    byte G_[] = {0x7e, 0x00, 0x81, 0x81, 0x81, 0x81, 0x91, 0x90, 0x72, 0};
    byte O_[] = {0x7e, 0x00, 0x81, 0x81, 0x81, 0x81, 0x81, 0x00, 0x7e, 0};

    byte La_[] = {0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0xff, 0};
    byte Ea_[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0};
    byte Ga_[] = {0x72, 0x90, 0x91, 0x81, 0x81, 0x81, 0x81, 0x00, 0x7e, 0};
    byte Oa_[] = {0x7e, 0x00, 0x81, 0x81, 0x81, 0x81, 0x81, 0x00, 0x7e, 0};

    byte N_[] = {0xff, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xff, 0};
    byte X_[] = {0x80, 0x41, 0x22, 0x14, 0x08, 0x14, 0x22, 0x41, 0x80, 0};
    byte T_[] = {0x01, 0x01, 0x01, 0x01, 0xff, 0x01, 0x01, 0x01, 0x01, 0};

As you can see, they listed out how the dots are configured. There's a max of 15 bytes (I assume including the null bit).

There's one more piece of code that we haven't talked about:

    for(int i=1; i<ArrayLen(WriteBuf); i++)
    {
       WriteBuf[i] ^= 0xff;
    }

So it goes through each bit, and does something to it. That is the shorthand for this:

    WriteBuf[i] = WriteBuf[i] ^ 0xff;

No, that is *not* an exponent. That is an exclusive OR, a *bitwise* operator. A bitwise operator is basically where it "overlays" the two binary sequences and it does a special computation on them. If the nth bit of each input number is 1 or the nth bit of each input number is 0, the nth output bit is 0. If the nth bit of one input number is 1 and the nth bit of the other input number is 0, then the nth bit of the output is 1.

Since 0xff = B11111111, it will essentially reverse the values of each bit. You can avoid this if you say that a bit set to *0* is on, instead of a bit set to *1* (like they do in the example code). A minor adjustment that just makes your life a bit easier :)

After that, you can write that array to the I2C bus and it should display the data!

  [1]: http://bricxcc.sourceforge.net/nbc/nxcdoc/nxcapi/group___array_functions_gae8d75e08c670f09f01200a897d7ed2ba.html


body:
I am using SPI to communicate with a IMU device which is working perfectly, except the SPISpeed which is not being altered as it should:

    unsigned int m_SPISpeed = 400000;
    SPI.begin();
    pinMode(m_SPISelect, OUTPUT);
    m_SPISettings = SPISettings(m_SPISpeed, MSBFIRST, SPI_MODE0);
    ...
    SPI.beginTransaction(m_SPISettings);
    digitalWrite(m_SPISelect, LOW);
    SPI.transfer(regAddr | 0x80);

Where `m_SPISpeed` is 400000. No matter what i set this value to it is always operating at `125000Hz`.

title: Unable to alter SPI speed on Arduino Micro

Answers: 1

body:
As was pointed out in the question comments, your use of **unsigned int** is the problem. The prototype for SPISettings is:

    SPISettings(uint32_t clock, uint8_t bitOrder, uint8_t dataMode) {

The comments in spi.h say:

    // We find the fastest clock that is less than or equal to the
    // given clock rate. The clock divider that results in clock_setting
    // is 2 ^^ (clock_div + 1). If nothing is slow enough, we'll use the
    // slowest (128 == 2 ^^ 7, so clock_div = 6).

So your SPI speed will be the processor speed divided by 128, which is 16 MHz divided by 128, being 125000 Hz, which is your observed result (since unsigned int cannot possibly hold more than 65535 on this platform).


body:
What is maximum voltage PWM pins can give?
can i give a vcc to 14v?

title: can i give a vcc to 14v?

Answers: 3

body: Since PWM pins are digital outputs, the maximum output voltage is VCC.

body:
On a typical Arduino board, PWM pins will theoretically only ever operate at ground (+0v) or `Vcc` (typically +5v). PWM is a square wave, which means it alternates rapidly between those two values, aka `LOW` and `HIGH`.

With that said, if you run it with a 50% duty cycle, then the **average** voltage over several cycles will work out as 50% of `Vcc` (i.e. typically 2.5v). The same applies to other percentages. It's important to note that it's not equivalent to a 'true' analog signal though, and shouldn't be used as such.

As a side note, there are some modified Arduino clones which have a voltage selection switch. These typically let the pins operate at either 3.3v or 5v, and should affect PWM (as far as I know).

body:
+5V

I understand for higher power people driving motors trigger a MOSFET transister which normally can go to 30 volts but this unit here appears to be able to switch 100 volts: https://www.banggood.com/100V-9_4A-FR120N-Isolated-MOSFET-MOS-Tube-FET-Relay-Module-For-Arduino-p-1396252.html this unit is likely to be able handle up to 50 Khz switching frequency (based on the regular MOSFET switching speed). Anything higher you'd need GaN (Gallium Nitride) transisters as used in Class D audio amps. Anyhow 100 volts and 9.4 amps would be 940 watts of DC, or maybe 664 watts of RMS sine wave (ball park), probably I would not trust more than 300 watts through that thing mind.


body:
I am building an electronic gadget eventually to sell.

I think the Atmega IC is used in the arduino and could this be programmed as easily as the arduino?

I'm wondering if I can use the chip and buy just what I need for my circuit, which would be cheaper as there would be no licensing obligations to the Arduino company

Cheers
Eamonn

title: Should I use an Arduino or not?

Answers: 6

body:
Short answer: Yes. After all, Arduinos are made by starting with an ATMega (or other AVR) IC.

Longer answer: People - including myself - routinely build with a bare ATMega328p (or other MCU), programming them off-board on another system, or providing connections to allow programming them in place. Beyond that you only need the soldering skills for the chip you choose (if you're building the boards yourself). I use DIP ICs and off the shelf through-hole PCBs and hand-build one or a couple at a time. Quad Flat-Package or Surface-Mount chips are another step up in complexity for the hand-builder.

body:
That's what I do all the time. You might want to buy an ISP programmer to program the chips (e.g. USBASP or usbtinyisp). If you just want to try things out first, you can use your arduino board as an programmer by uploading the ArduinoISP sketch.

The Arduino Uno uses an ATMega328, but you could use other AVR chips too. E.g. the ATMega8, which is slightly cheaper. Or an ATTiny85, which only has a few pins, and is therefor a lot smaller (also cheaper). So you can choose a chip that best fits your needs.

body:
I'd like to second the other posts - if you are familiar with Arduino, going to a stand-alone chip is very easy.

You miss out on the following things: programming via USB, 7-12volts through the power jack, and/or power through USB, reset button, led on pin 13, and the clock. Depending on where you get your Atmel chip, you may also need to set the fuses.

The code is exactly the same, even if you go down to a smaller chip (or larger - whatever suits your project best!).

Programming: I use a FreeTronics ICSP (ISP) to program the chips, and have the 6-pin ICSP header on all my projects for easy reprogramming. This particular programmer has a "slow clock" jumper, because when you get the chip from the Atmel factory, their internal clock runs at 1mhz, too slow to program with the Arduino IDE default settings. You can leave it at 1mhz, if your project doesn't need any more, or change the fuses. You will need an ICSP to set the fuses (see further down). By using an ISP rather than usb, you also save a little memory - you don't need a bootloader (which is pre-programmed on Arduinos, but not when you buy the chips from the factory).

You will need to sort out your own power - this depends on what you need, and what you have. You can use a 5-volt AC-DC power supply ("Wall wart") and plug it into mains. Or, you can power it off USB - if you only use USB for power, you can solder the socket directly on your board. You can use a regulator (which is what the Arduino uses for the 7-12v power socket), or, if running it off a 12v power supply, it might be easier/cheaper to buy a car phone charger from the dollar store, and a lot of the work will be done for you. Also, the power supply doesn't have to be 5v - depending on your application, you might run it from 5.5v to as little as 1.8v, depending on your clock speed. Find the data sheet for the chip you use.

A reset button is very easy to add, if you need it - all it takes is a resistor and a pushbutton. Weather you need it or not, depends on your project.

The same applies to the led on pin 13 - it depends on your project.

Finally, the clock. The Arduino has a 16mhz quartz clock. You can do the same, it only takes 3 components (you will have to set the fuses, see further down). You can use a clock up to 20mhz, giving you a 25% speed boost if you need it (you may need to change some settings, because timing functions like delay depend on the clock speed - your delays will be 25% shorter). Or, you can use the internal 8mhz clock (either at full speed, or as from factory, at 1/8 speed, so you get 1mhz). At 4mhz or less, you can run the Atmega at 1.8 volt, or 0.7 volt for the "pico power" chips.

As I have mentioned, you may need to set the fuses to the correct value. The best idea is to go to http://www.engbedded.com/fusecalc/ to work out what fuse settings you want. Specific things to look for: the clock source (internal or external? what speed?), divide clock by 8 internally, and brown-out detection (Arduino chips turn themselves off when the power goes below 4.3v). Warning: setting wrong fuses may set your chip so it is very difficult to fix. You can set the fuses using an ISP; if the clock speed is very slow (I think < 4mhz? which it is when it comes from the factory), then you will have to "slow program" - some ISPs have a "slow program" jumper, but you can use an option to avrdude to do the same - I think it's -B e.g. -B10).

body: Arduino of course started as a prototyping platform. Build this first, get it working, then move to a circuit board of your own design with the same chip and go from there. However, as the cost of all the components and really the boards themselves drops, I frequently find my self thinking, why not just use the board. Obviously if you are going to market something, having a full arduino in there might be a bit much, but if its just for your own application, I don't see any reason why you wouldn't just buy boards and use them as necessary.

body:
Thanks for all the replys. I have a lot to learn as I only heard of arduino a month ago.
Didn't have a reason before.
My arduino hasn't arrived yet so I made my basic circuit with components on a breadboard.
I think I will need the arduino as I need some monitoring in the circuit.

Thanks again much appreciated.
Eamonn

body:
Since you are already using Arduino, I think you not should use atmega, but must! To prevent future headaches, since you look new to electronics, I HIGHLY recommend to check for app notes by Atmel. Just type it "Atmel app notes" at google and you will find a lot of useful tips. Some of them are start to routing by crystal resonator, them GND and Vcc. Use, if possible, on each IC a 100nF ceramic SMT capacitor nearest as possible and another one of 10uF (can be electrolytic) on most robust ones (like microcontroler). Always route opposite signals (like Vcc and GND) tied together with the same size to low its impedance... If you are doing with high inductance loads you should use another sorce (and maybe also a diode as rectifier or an optocoupler).

There's a lot of good practices and if you want to sell your work, you really have to study them.

Good luck! Also look for the electronics SE


body: I am trying to connect an Arduino and Raspberry Pi over USB.  I would like to send serial commands, just like the serial monitor in the Arduino IDE.  I know how to do this on the Arduino end but I'm not sure how to send/receive serial communication on the Pi end.  Ideally the solution would utilize Python.

title: Arduino Raspberry Pi USB Communication

Answers: 3

body:
You would be better to ask this on http://raspberrypi.stackexchange.com

You can use program `minicom` on the Pi; this is a terminal program like the serial monitor in the Arduino IDE, and of course you can use Arduino IDE on the Pi.

If you look at the Pi site you will see lots of Python serial communication programs.

body: Why do you want to use the USB port on the Pi? Isn't it easier to connect the Arduino directly to the UART pins (Pins 8 and 10) on the PI and then read out the UART in your python programme?

body:
You will need PySerial to accomplish this. A tutorial on interfacing Arduino and the RPi using a usb can be found [here][1]

  [1]: http://blog.oscarliang.net/connect-raspberry-pi-and-arduino-usb-cable/


body:
    #include "sha256.h"

    uint8_t hmacKey1[]={
    0x65,0x63,0x73,0x74,0x61,0x63,0x79
    };

    void printHash(uint8_t* hash) {
    int i;
     for (i=0; i<32; i++) {
       Serial.print("0123456789abcdef"[hash[i]>>4]);
       Serial.print("0123456789abcdef"[hash[i]&0xf]);
      }
     Serial.println();
    }

    void setup() {
       uint8_t* hash;
       uint32_t a;

     Serial.begin(9600);

     // HMAC tests
      Serial.println("Test: RFC4231 4.2");

    Serial.print("Result:");
    Sha256.initHmac(hmacKey1,20);
    Sha256.print("Hi There");
     //My TRIAL ATTEMPT
     int i;
     for (i=0; i<32; i++) {
     hash[i] =Sha256.resultHmac();
     Serial.println(hash[i]);
     }
    }

How do I save the hashed result into a variable? I disregarded the Printhash function above and tried it with my own code but it displays

     sketch_feb14a:32: error: invalid conversion from 'uint8_t*' to 'unsigned char'

I don't understand the printhash function above and found little to no documentation on the web. I'm thinking of using AES library but I guess it's more complicated over here. The above code is based on Spaniako's CryptoSuite [here][1]

Heading
=======

  [1]: https://github.com/spaniakos/Cryptosuite "here"

title: How to save the SHA256 with HMAC into a variable instead of serial print?

Answers: 2

body: The hash is a series of binary digits. They are usually represented in hexadecimal form for readibility. You are just printing out the raw bytes, which will give a series of random ASCII characters. Some of these may be control characters which interfere with serial port communication.

body:
My solution was making a new function that returns a String with the hash

    String GetHash256(uint8_t* hash) {
     char tmp[16];
     String sHash256 = "";

     int i;
     for (i=0; i<32; i++) {
      sprintf(tmp, "%.2X",hash[i]);
      sHash256.concat(tmp);
     }

     return sHash256 ;
    }


body:
From what i've researched here is my thoughts on both

1. C++
I heard that you can create libraries using C++ in arduino. And you can use the Arduino IDE to do that stuff.  Here is the proof

http://arduino.cc/en/Hacking/LibraryTutorial

Notice that it uses the C++ syntax.

I also see arduino projects on github written on C++
https://github.com/search?l=C++&q=Arduino&type=Repositories&utf8=✓

2. C

I heard that you can use AVR GCC and code it without the arduino ide. And I heard it's much faster than the arduino language because it's more closer to the metal. But I think it's harder to set up because you need a programmer into the Atmel chip, which is much more costlier compared to directly plugging in the arduino using the USB to printer cable. And you also need to download a bunch of stuff to get coding in pure avr gcc (win-Avr GCC, atmel studio etc.).

Which one should i learn C or C++? I prefer the easy to debug route. Or is it beneficial if i learn both?

title: New to Arduino: Should I learn C, C++ or both (C & C++)?

Answers: 4

body:
Arduino supports c++, but does not support many of the standard libraries.
The vast bulk of the functions in the Arduino IDE are c functions.

You can do almost everything in c, except for a few advanced items.

Due to the limited c++ libraries it will be difficult to learn c++ on Arduino; indeed it is not the ideal platform to learn c, as most of the tutorials will not work (because there is no I/O on Arduino).

body:
The basic syntax of C and C++ is very similar, to the point that C code can typically be compiled directly as C++. You'll also find C standard functions (such as `printf` and `malloc`) can be used from C++ programs.

The major difference in the core language is that C++ has a lot of extra stuff such as classes and templates. Conventionally, C++ also has a huge standard library which doesn't work on C. However, that's not usually available (nor really appropriate) for Arduino programming, so you don't need to worry too much about it unless you migrate to e.g. desktop programming.

Basically, it's probably sensible to learn C first, because the same knowledge works in C++. You can then move on to the C++-specific stuff, such as classes.

As a side note, the Gnu Compiler Collection (GCC) actually covers both C and C++. It's what the Arduino IDE at Atmel Studio use under-the-hood for all their compilation. It's even possible to work directly with GCC but still upload programs to Arduino via USB.

It's also worth noting that programs compiled within the Arduino IDE aren't necessarily going to run any slower than programs compiled some other way (whether C or C++). The main difference is whether or not you use the Arduino functions. Since they are general purpose, they're not necessarily doing things the most optimal way. You could get more efficiency in theory by manipulating the microcontroller's special registers directly, which is you can do from within the Arduino IDE as well. It's usually very tricky for a beginner though, so it's probably not something you want to attempt until you're more comfortable with C/C++.

body: For starting out? I would say neither. The arduino IDE is based on a programming language called processing. Which you can look at. Honestly, if you have done any programming in the past you will be fine for the basics. The advanced stuff might make you look at working with c++ files. But there is nothinging overly complex there. A lot of the add-on hardware that you can purchase comes with existing arduino libraries. Use these as a baseline.

body:
@ConnorWolf Way too kind.

Arduino is based on Wiring, which is based on Processing, which is a kludge of Java, resembling C++ running on an embedded prototyping platform ill suited for learning programming by any Definition.  Many libraries half written and confusing, implementing only as much as the original author needed, not the entire spec (SPI being a great example).

Get a Pi for the same price, at least it is an end user computer for poor people.

Besides, if you have something that can run the Ardunino IDE why are you learning to program on an Arduino? You need to be proficient in C or C++ before you attempt anything for real on an Arduino. Blinking lights is fine, beyond that, good luck.

Learn C or C++ (preferred as it is newer) on what you have, then start using the Arduino. Eclipse or Microsoft Visual Studio Community are both free and support both languages. (Both also support Arduino development when the time comes, avoid the Arduino IDE it is terrible). There are enough samples for either to keep you busy for a long time. Embedded programming REQUIRES understanding of low level hardware and IS NOT suitable for learning.

Forget modern debugging. Paid engineers grumble when they have to do it and it cost a decent price for the enabling hardware. Stick to the old fashioned printf debugging style.


body:
I am trying to connect SD card with arduino without using a shield. To convert to 3.3v, I have used voltage divider circuit as described in these two sites:

http://garagelab.com/profiles/blogs/tutorial-how-to-use-sd-card-with-arduino

http://www.martin-gardner.co.uk/how-to-connect-your-old-sd-card-to-an-arduino/

When I uploaded the code i got the following error on serial monitor:

Initializing SD card...initialization done.

error opening test.txt
error opening test.txt

title: Interfacing SD card with arduino without shield

Answers: 0


body:
How can I fix error code 10 while installing the device driver for Arduino in Windows 8.1?
The LED on the board is blinking after connecting it to the laptop, so I don't think so that the board is damaged. What is the cause of this issue?

title: Error code 10 for arduino device driver

Answers: 4

body:
First of all, test if you even need a new driver. On Windows, the Arduino drivers for my Uno and my Mega were installed automatically by Windows. I'd advise to restart your computer, ***using the actual restart button, not manually shutting off and turning on... this is very important with Windows 8.1 and its Hybrid Boot default!!!*** A normal reboot doesn't fully reload all of the drivers. Next, open the Arduino IDE, and then see if you can successfully upload the "blink" example sketch.

If that doesn't work, let's try something else.

First of all, open up Device Manager and find your device:

> ![Device manager][1]

It should be under the *Ports (COM & LPT)* section. After that, right click and click on *Properties*.

> ![Right click menu][2]

Then, let's go to the *Driver* tab and click on *Update Driver*. Then, click on *Search Online Automatically for this Driver.*

> ![Properties Window][3]

First, try seeing if an automatic update finds any drivers capable. If not, I've found previously that there's sometimes a *Reinstall* or *Fix* button somewhere if the driver isn't working correctly.

In addition, you can also update it manually using Device Manager. Instead of clicking on *Search Online Automatically for this Driver,* click *Browse My Computer Manually.* For me, there was a Mega driver under the *Let me pick from a list of compatible device drivers on my computer* and there was a Mega driver for me (although I don't know if that's because I have it installed already).

You can also use that same menu to point it to the location of the installation of the Arduino IDE and it will search for any compatible drivers.

Rolling back the driver is another option if the Arduino IDE tried to install a faulty driver that somehow got corrupt over a working driver installed by the computer.

The last thing I would suggest trying as a last resort is using the *Uninstall Driver* button and then trying to reinstall the driver manually. I've never done this with an Arduino board, although there have been some times with other drivers that this has helped to remove the faulty driver.

If none of this works, it may be a faulty board.

  [1]: https://i.stack.imgur.com/v8Q0A.png
  [2]: https://i.stack.imgur.com/RUPKR.png
  [3]: https://i.stack.imgur.com/FHjqo.png

body: After wasting a huge amount of time trying get the Arduino IDE to upload the sketches to my new starter robot I came across the following document in the Arduino Website :"Guide to the Arduino Leonardo and Micro"... In this document they explain how the serial port communication work on the leonardo (which is the ME-Baseboard from MakeBlock)...They state that auto-reset is initiated when the computer opens the serial port at 1200 baud and then closes it... Whatever that means... I went into the makeblock driver setting (under windows 8.1 device manger) and change the baud rate to 1200... Surprise surprise... all  works fine now, I can compile and upload the sketches for the starter robot... What frustration !!!! And for the people at Makeblock... I have been trying to create a community userid and while the system say that it will send me an email, it never does !!!

body: I am sad to report that what actually happened it that changing the baud rate also led to a change in board type in the arduino IDE... So the sketch did compile and load but assuming that the board is a UNO.  End result, still facing same problem and robot behave a bit erratically probably because the upload was not performed for a leonardo board.  I have tried counless times with countless different procedures on an acer laptop with Windows 8.1, an acer laptop with Windows 7 and a surface pro with Windows 7.  Same problem everywhere.  If someone from Makeblock read this blog, I would appreciate if you could send me the validating email so I engage this troubleshooting process on their community discussion board.

body:
I had the same issue. The drivers, which shipped with Arduino IDE didn't work for me.

Actually, the reason was that I was using Arduino UNO clone. And it required another driver.
This video helped me to find the answer: https://www.youtube.com/watch?v=r9MGJ16pRLc

In my case I had to install the CH340 chipset usb driver. The driver can be downloaded from this page: http://www.microcontrols.org/arduino-uno-clone-ch340-ch341-chipset-usb-drivers/

After I installed CH340 driver, the upload from Arduino IDE started working perfectly.


body:
I am working on my project of home automation system using Arduino GSM SIM900 & four channel relay module. I am facing a problem in my code. Can any one help me on this, SMS is receiving but its not switching the relays?

    #include <SoftwareSerial.h>

    // EN: String buffer for the GPRS shield message
    String msg = String("");
    // EN: Set to 1 when the next GPRS shield message will contains the SMS message
    int SmsContentFlag = 0;
    //control pins of relay.
    int relay_a=4;
    int relay_b=5;
    int relay_c=6;
    int relay_d=7;

    // EN: Code PIN of the SIM card (if applied)
    //String SIM_PIN_CODE = String( "XXXX" );

    void setup()
    {
      Serial.begin(19200);                 // the GPRS baud rate
      // Initialize  PINs
      pinMode( 4, OUTPUT );
      pinMode( 5, OUTPUT );
      pinMode( 6, OUTPUT );
      pinMode( 7, OUTPUT );
      digitalWrite( 4, LOW );
      digitalWrite( 5, LOW );
      digitalWrite( 6, LOW );
      digitalWrite( 7, LOW );
     Serial.println( "AT+CMGF=1" );
     delay(200);
    }

    void loop()
    {
        char SerialInByte;
        if(Serial.available())
        {
            SerialInByte = (unsigned char)Serial.read();
           delay(5);

            // -------------------------------------------------------------------
            // EN: Program also listen to the GPRS shield message.
            // -------------------------------------------------------------------
           // EN: If the message ends with <CR> then process the message
            if( SerialInByte == 13 ){
              // EN: Store the char into the message buffer
              ProcessGprsMsg();
             }
             if( SerialInByte == 10 ){
                // EN: Skip Line feed
             }
             else {
               // EN: store the current character in the message string buffer
               msg += String(SerialInByte);
             }
         }
    }
    // EN: Make action based on the content of the SMS.
    //     Notice than SMS content is the result of the processing of several GPRS shield messages.
    void ProcessSms( String sms ){

      if( sms.indexOf("ona") >= 0 ){
        digitalWrite( relay_a, HIGH );
      }
       if( sms.indexOf("onb") >= 0 ){
        digitalWrite(  relay_b, HIGH );
      }
       if( sms.indexOf("onc") >= 0 ){
        digitalWrite(  relay_c, HIGH );
      }
      if( sms.indexOf("ond") >= 0 ){
        digitalWrite(  relay_d, HIGH );
      }
      if( sms.indexOf("offa") >= 0 ){
        digitalWrite(  relay_a, LOW );
      }
      if( sms.indexOf("offb") >= 0 ){
        digitalWrite(  relay_b, LOW );
      }
      if( sms.indexOf("offc") >= 0 ){
        digitalWrite(  relay_c, LOW );
      }
      if( sms.indexOf("offd") >= 0 ){
        digitalWrite(  relay_d, LOW );
      }
    }
    // EN: Request Text Mode for SMS messaging
    void GprsTextModeSMS(){
      Serial.println( "AT+CMGF=1" );
    }

    void GprsReadSmsStore( String SmsStorePos ){
      Serial.print( "AT+CMGR=" );
      Serial.println( SmsStorePos );
    }

    // EN: Clear the GPRS shield message buffer
    void ClearGprsMsg(){
      msg = "";
    }

    // EN: interpret the GPRS shield message and act appropiately
    void ProcessGprsMsg() {
      if( msg.indexOf( "Call Ready" ) >= 0 ){
       //  Serial.println( "*** GPRS Shield registered on Mobile Network ***" );
         GprsTextModeSMS();
      }

      // EN: unsolicited message received when getting a SMS message
      if( msg.indexOf( "+CMTI" ) >= 0 ){
       //  Serial.println( "*** SMS Received ***" );
         // EN: Look for the coma in the full message (+CMTI: "SM",6)
         //     In the sample, the SMS is stored at position 6
         int iPos = msg.indexOf( "," );
         String SmsStorePos = msg.substring( iPos+1 );
       //  Serial.print( "SMS stored at " );
      //   Serial.println( SmsStorePos );
         // EN: Ask to read the SMS store
         GprsReadSmsStore( SmsStorePos );
      }

      // EN: SMS store readed through UART (result of GprsReadSmsStore request)
      if( msg.indexOf( "+CMGR:" ) >= 0 ){
        // EN: Next message will contains the BODY of SMS
        SmsContentFlag = 1;
        // EN: Following lines are essentiel to not clear the flag!
        ClearGprsMsg();
        return;
      }

      // EN: +CMGR message just before indicate that the following GRPS Shield message
      //     (this message) will contains the SMS body
      if( SmsContentFlag == 1 ){
     //   Serial.println( "*** SMS MESSAGE CONTENT ***" );
     //   Serial.println( msg );
     //   Serial.println( "*** END OF SMS MESSAGE ***" );
        ProcessSms( msg );
      }

      ClearGprsMsg();
      // EN: Always clear the flag
      SmsContentFlag = 0;
    }

title: Arduino Based Home Automation System

Answers: 1

body:
I think you'd want to include a call to `ClearGprsMsg()` right before the line `GprsReadSmsStore( SmsStorePos );`.

Then, `msg += String(SerialInByte);` is probably wrong, see for example http://arduino.cc/en/Tutorial/StringConstructors:

    // using a constant integer:
    stringOne =  String(13);
    Serial.println(stringOne);      // prints "13"


body:
There is a function on one of my programs I want to be switch on and off by pressing a button. The button is unbiased otherwise I would set the function to read the button's status of HIGH or LOW.

So I need to create variable named "switch" with an initial value of 0. Then I would create a function would read if buttonPin is HIGH change the value of "switch" by +1. Next time the buttonPin is HIGH change the value by -1 so that every time the button is pressed the value of "switch" alternates between 1 and 0. Now before my loop calls the function I want on or off it can compare the value of "switch" and run or not run the function.

I don't know how to express this in the Arduino sketch. I'm am also open to alternate ways of achieving the same result.

title: Program button to switch between two values

Answers: 2

body:
Pseudocode:

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

body:
It sounds like you are using a number as a boolean (true/false) value.

You might consider using a a boolean instead.

    boolean value = false;
    if button is pressed {
        value=!value
    }
    if value {
        // do something here.
    }

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