text:
Cannot program Arduino Micro in OSX without hard resetting the board every time
I am experiencing a problem when programming Arduino Micro in OSX Mavericks. I have tried to reproduce this problem in XCode and Arduino IDE and it is persistent. I need to make a hard-reset at the same time as a click the "program" button.
I have tried to use the new Leonardo bootloader to see if it solves my issue, but its still persistent.
I am running avrdude 6.1, what is the problem?
Stacktrace:
---- Size ----

Binary sketch size:   24162 bytes (of a 28672 byte maximum)
Estimated SRAM used:  733 bytes (of a 2560 byte maximum)
Elapsed time: 5.2 s

---- Reset ----

screen -X kill

No screen session found.

make: [reset] Error 1 (ignored)

sleep 1

9.2-RESET:  <   micro   ./ ./

stty -f /dev/tty.usbmodem1411 1200

---- Upload ----

10.6-UPLOAD:  <     micro   ./

/Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/bin/avrdude -patmega32u4 -C/Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/etc/avrdude.conf -D -cavr109 -b57600 -P/dev/tty.usbmodem1411 -Uflash:w:Builds/embeddedcomputing.hex:i

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

Try updating the bootloader. Also, is the problem also present on none-OSX systems?

@Gerben, i have tried updating it, still the same result. I am considering trying Leonardo bootloader instead to see if it does any good.

This Arduino.cc article describes the differences between Leonard & Micro vs. other Arduinos, including the fact that Micro does not have a separate USB processor on board but creates a virtual USB with the main processor. There is no (or a very different) auto-reset mechanism. There is apparently a way for the IDE to open the Mac's USB at 1200 baud to cause the Micro to reset; then the IDE can wait for the virtual USB to re-appear. But it also says you may need to use the reset button suggesting the 1200 baud dance doesn't work all that reliably.

Thats how far i have reached so far, but unfortunately it does not solve my problem as resetting manually every time i am uploading a sketch is a pain in the @$$.

I believe the reliability of the reset depends on the sketch (i.e. that it's possible to write code that inadvertently disables the auto reset code). Have you tried reproducing this with e.g. a blink sketch?


text:
Unable to flash bootloader on ATmega32U4 with AVR dragon
I am flashing a naked ATmega32U4, but the process fails in the end where it is verifying.
avrdude -c dragon_isp -p m32u4 -P usb -U flash:w:Caterina-Micro.hex -U lfuse:w:0xff:m -U hfuse:w:0xd8:m -U efuse:w:0xcb:m -U lock:w:0x2f:m -v -B 100

avrdude: Version 6.1, compiled on Mar 23 2014 at 04:42:55
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/usr/local/Cellar/avrdude/6.1/etc/avrdude.conf"
         User configuration file is "/Users/SomeUser/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : usb
         Using Programmer              : dragon_isp
         Setting bit clk period        : 100.0
avrdude: usbdev_open(): Found AVRDRAGON, serno: 00A200050468
JTAG ICE mkII sign-on message:
Communications protocol version: 1
M_MCU:
  boot-loader FW version:        255
  firmware version:              7.38
  hardware version:              1
S_MCU:
  boot-loader FW version:        255
  firmware version:              7.38
  hardware version:              7
Serial number:                   00:a2:00:05:04:68
Device ID:                       AVRDRAGON
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

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

         Programmer Type : DRAGON_ISP
         Description     : Atmel AVR Dragon in ISP mode
         Vtarget         : 5.0 V
         SCK period      : 100.37 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.16s

avrdude: Device signature = 0x1e9587
avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as D8
avrdude: safemode: efuse reads as CB
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: reading input file "Caterina-Micro.hex"
avrdude: input file Caterina-Micro.hex auto detected as Intel Hex
avrdude: writing flash (32730 bytes):

Writing | ################################################## | 100% 62.28s

avrdude: 32730 bytes of flash written
avrdude: verifying flash memory against Caterina-Micro.hex:
avrdude: load data flash data from input file Caterina-Micro.hex:
avrdude: input file Caterina-Micro.hex auto detected as Intel Hex
avrdude: input file Caterina-Micro.hex contains 32730 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 152.35s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0002
         0x66 != 0x6e
avrdude: verification error; content mismatch

avrdude: safemode: lfuse reads as FF
avrdude: safemode: Verify error - unable to read hfuse properly. Programmer may not be reliable.
avrdude: safemode: lfuse reads as FF
avrdude: safemode: Verify error - unable to read hfuse properly. Programmer may not be reliable.
avrdude: safemode: Sorry, reading back fuses was unreliable. I have given up and exited programming mode

avrdude done.  Thank you.

I get another verification error when i program without fuses:
avrdude -c dragon_isp -p atmega32u4 -P usb -U flash:w:Caterina-Micro.hex -u

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.16s

avrdude: Device signature = 0x1e9587
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: reading input file "Caterina-Micro.hex"
avrdude: input file Caterina-Micro.hex auto detected as Intel Hex
avrdude: writing flash (32730 bytes):

Writing | ################################################## | 100% 69.60s

avrdude: 32730 bytes of flash written
avrdude: verifying flash memory against Caterina-Micro.hex:
avrdude: load data flash data from input file Caterina-Micro.hex:
avrdude: input file Caterina-Micro.hex auto detected as Intel Hex
avrdude: input file Caterina-Micro.hex contains 32730 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 178.10s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0000
         0x04 != 0x0c
avrdude: verification error; content mismatch

avrdude done.  Thank you.

can you try without setting the fuses?

Have you retried the same command several times? It can happen sometimes that the command fails due to a bad serial connection.

@Treesrule14, i tried without the fuses and the result is the same. Verification error. Although it seems like something goes right as the boards LED starts blinking. But i am absolutely not confident with the flashing.

@jfpoilpret, i have tried so many times that i stopped counting :-/

Does your board have any additional curcuitry connected to the SPI pins?

Try setting only the fuses first. By default the 32u4 runs at 1Mhz I belief. Try lowering the programming speed using -B 10 (not sure if this works for the dragon; I have to use this parameter when programming blank AVRs using my usbASP programmer).

@ChrisStratton, yes i have and there are 100Ohm resistors between the peripheral connected.

@Gerben, i have tried setting the -B flag but the results are extremely inconsistent. I am afraid that the AVR dragon is not playing nicely in OSX. Tommorow i will get my hands on a Atmel-ICE and see if it will play with me.

100 ohms may well not be enough to prevent interference with programming.

@ChrisStratton, how much is recommended?

@ChrisStratton, how much is recommended? I have MPU-9250 IMU connected to the SPI line, where there is 100Ohm resistors in series with that device.

If there is any way it could be driving signals (or clamping them? Is it powered? At what voltage?) I would want at least 1K.  Maybe best as a temporary test to remove the resistors to entirely break the connection and experiment with programming that way for an hour or two.

I literally gave up and got myself a Atmel-ICE which solved all my problems.

I think you need to pass the option -u to disable safe mode, see the avrdude documentation. Under the -u option the manual states:

If you want to change fuses you will need to specify this option

I tried to pass avrdude -c dragon_isp -p m32u4 -P usb -u -U flash:w:Caterina-Micro.hex -U lfuse:w:0xff:m -U hfuse:w:0xd8:m -U efuse:w:0xcb:m -U lock:w:0x2f:m with the -u option, but instead i am getting a bunch of avrdude: stk500v2_jtagmkII_recv(): failed. On the SPI line i also have another SPI device connected, which is seperated by 100Ohm resistors, so i am not expecting that its causing any problems?

I remember getting that same error programming with the dragon via avrdude. From memory, it was due to some kind of wiring problem. Not sure about the other SPI device, but working with the simplest possible circuit will always make it easier to debug.

ISP wiring problem perhaps? The thing is that the bootloader has been uploaded to the MCU once in a while, which is quite odd if theres a wiring error.

I meant a bad connection, which may still work intermittently

I will try to change the ISP cable and see if it does anything. I have changed USB cables just to verify that its not an issue.

I have updated my post. Its as if i flash the bootloader, it is extremely hard to reflash it afterwards. Im powering it with USB.

source: Stack Exchange

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

sort: votes


text:
estimating battery run time
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);
}

First don't use 9V batteries to power motors, they don't contain enough energy to last long. Then, consider using ATmega328 sleep modes (you can wake it on an input pin value, eg your button). Finally, consider ditching the UNO altogether and replace it with a minimal circuit (Arduino boards are not optimized for low consumption, but they are good forprototyping).

I agree. 9V batteries also don't have enough discharge capacity for driving things that need more than a few 100 mA. You can use high capacity AAs for that (NiMH cells for example - but beware of their high self-discharge rates, that may offset any economy you gain by configuring the MCU into low power mode). Also, the voltage regulator on the Uno will consume all of your battery, no matter how you configure the '328 for low power consumption. See this great answer by Anindo Ghosh for more details.

You would have to disengage the servo, when it's done moving. Otherwise it will continue to draw power. You also can't put the arduino in sleep mode, while the servo is attached, as it needs to be sent position data continuously. In case there is some pressure on the servo; if you connect the gnd and vcc of the servo, it will act like a break.

@jfpoilpret - I will look into the ATmega328 - as far as replacing it with a minimal circuit - I'm afraid my current circuitry knowledge is limited - I'm not even sure I would know where to get started with that. Can you explain or link me to anything that explains how to replace an arduino with a circuit?

ATmega328 is the central intelligence of Arduino UNO. UNO brings a lot of extra stuff that majes it cool for prototyping but not for definitive circuits: typically you won't need USB in the definitive circuit, you won't need voltage regulator if you provide voltage with bateries under 5V overall. For links, google is your firend :-)aybe start with "Arduino on breadboard" that will show you simple circuits to start with.

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); 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.

Jon - thanks - can you explain a little bit more about an interrupt or link to something where I can learn more about how to set this up?

Please visit this link from Arduino.cc; the "Using Interrupts" section says it perfectly: http://arduino.cc/en/Reference/AttachInterrupt

Additional: http://gammon.com.au/interrupts

added psuedocode-ish interrupt scenario

If you have issues with the interrupt going off multiple times when you press the button once, search for "how to debounce a button"

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, 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.

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


text:
Can i use arduino code, without using arduino board but just using MCU included
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)

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.

Does arduino coding enviroment generate Hex file? Normally i was Pic, Intel user however, i did not see the compiler generate hex file. Should i need to use just its library and insert into another coding environment and how?

Other questions on this site discuss both the .hex file and the use of alternate development environments.

Actually, i am not asking hex file issue, i am asking that if we use USB-serial circutry, and just burn bootloader to the MCU via this then just upload the code we wrote... doesn't it work for all arduino used MCU's ??

Why would you add the cost of a serial interface to your product instead of using the built-in ISP capability?

Yes actually, i can use my arduino to code the MCU...

to be direct... i wonder if i can use the method http://arduino.cc/en/Main/Standalone to programme ATmega2560 used in arduino mega?

There is no need for a bootloader if you stick with ISP.

Ignacio said everything is needed. Just search on google :) You can use programmer like khazama.
Also you can use arduino board to program atmel chips.
Using an Arduino as an AVR ISP
And now you need only .hex file to upload to your chip
How to find .HEX
I just want to point out one thing. Do not play with lock bits:)

@PeterR.Bloomfield :))

I know khazama. Such uploaders also used for PIC microcontrollers 16F877 etc. I have already used them, but i am planning to use the chip in arduino MEGA or Leonardo, which are surface mount...
Therefore, it seems that i need to use ISP...

Thats not right. You can use USB-TTL converter like it is done in Arduino. There are many schematics and tutorials how to write bootloader and so on. Surface mount you mean mega2560 TQFP package? I do not understand your argument.

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.

Upload the Arduino ISP Sketch to your Arduino board's MCU.
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. You can find similar datasheets if you're using other MCUs.)
Write your code
Click "File>Upload using programmer" or just press Ctrl + Shift + U.
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
Hope this helps.


text:
fast memory buffer and setting output state
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.

What are you sampling / delaying with your project? how many bits is each sample?

@portforwardpodcast The idea is to signal two 3-phase IGBT's and be able to balance them independently, so be able to delay 1 set of three pulses relative to the other. The arduino is not generating the PWM's but simply intercepting them from a drive's circuit board and the outputting them.

So you are buffering 1 bit samples. It may sound counter intuitive but using a full byte to store a single bit May give more performance. This is because you avoid shifts and are just doing simple memory lookups. @amandoninc 's answer is correct, just use an array. As far as hand coding assembly i disagree. I bet you could get away with an output compare interrupt. Please comment back if you need more help

@portforwardpodcast Thanks, I'll give it a try and find out. At this stage the project is on hold but it's great to know how to move forward from here.

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).


text:
Arduino ProMini green led flashing and unable to reset
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 "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!

Have you measured the Vin voltage when this happens?

Your solar system must not provide more voltage than the Arduino is designed for, and when the voltage falls too low the system must reset properly - usually by using a brownout detector function.


text:
Simulink with arduino : data acquisition
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?

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.

Thanks a lot :) , i'm actually using an ARDUINO uno but it give an error when i try to deploy the s-function i will try with an ARDUINO MEGA but please can you send me the s-function that you have built to chfakht@gmail.com , it will be very helpful ;)

@user3530803 Does that error look like "you should enable external mode in parameter configuration"? I had this kind of error before and went to MEGA then. You can supply your error message to your question, maybe someone can help you solve that using just UNO. I am on vacation these days, about 5 days later I will share the detail source code in my answer.

Thanks , i have update the post : you can see the error in the now , have a good vacation i will be waiting you

@user3530803 I just updated my answer with source code of s-function.

thanks a lot , i have just done it with the s-function but this time with an ARDUINO MEGA ... please can you tell me for what kind of project you have used the s-function ... here is my email for further contact : chfakht@gmail.com

Not working, whatever I try, it keeps giving this error. "Error(s) encountered while building "I2C_reading_test":
Failed to generate all binary outputs.
Component:Simulink | Category:Modelerror
"
Any idea from what it comes?

@Andrei you may search this error on google. I do not have a simulink to check your code currently. Sorry


text:
use shiftIn and shiftOut with attiny85
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!

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 or hardware 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.


text:
Pulse measurement
I am currently doing the project in pulse measurement using an Arduino Yún. 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)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

pulsePin is declared twice too.


text:
Arduino program wont work properly for some reason
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.

Can you show us your circuit?

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:
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.)

My arduino is nano. And the problem is that the forward and left pins are supposed to work and they dont, instead of the backward and right works. So what happens is, I upload this program to my arduino and get my circuit. I plug the any of the function cables, which are forward backward, left, and right to the pins 12 and 10, and they dont work. However, when I plug the any of the cables into pins 9 and 11 which are right and backward, they work! I even tried with LED for 12 and 9 and it did not work. However, LED flashes with the pins 11 and 10. So I dont really know what is the problem.

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). ;)

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.


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

#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?

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.

lcd.clear(); is a better option. thanks for helping @peter


text:
create a interruption-proof power
I need to create a interruption-proof power for a project of mine, very similar to the design of this link.
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?

See @Jon's recommended Sparkfun charger - this can be adapted to 12V operation (set to 13.7V) by changing  R7 in Sparkfin's circuit diagram. Some other changes will be needed but the IC is made to work with both LiIon and Lead Acid batteries. **LT3652 data sheet here

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)

(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.

As a supplement, there are pre-made buck regulators specifically designed for all of your requirements; i.e. micro-power (solar/wind/vib), charge the battery when it's able, use the battery at night, etc.   An example MPPT (for a single-cell lipo) https://www.sparkfun.com/products/12885

@Jon The LT3652 that Sparkfun use is quite a good match to this application. It is able to be adapted to a 12V SLA battery by a resistor change and Vin of 32V is high enough. | The MPPT method used is proxy one - they hold V_PV at some fraction of V_PV_OC BUT they claim to get within 2% o true MPPT. (I've meant to try these for some while but not yet done so).

I wish Sparkfun would give me free samples like Linear does :)


text:
Combining & averaging magnetometer values
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:
#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: %6d %6d %6d    M: %6d %6d %6d",
    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.

Also consider a rolling average where you take eg New_AVG = 10% x latest_reading  + 90% of Old_AVG. (Or 1/N of reading + (N-1)/N of old value for N samples. ) This behaves rather differently than you may expect and is smoother than just averaging N samples. Easyish to implement. | OLD=AVG; AVG = OLD x (n-1)/N + Sample/n .

Thanks Russell - I managed to use a Unity plugin to use the accelerometer in my android phone to remotely control the virtual object on my main monitor in Unity. I would now like to trigger an event based on a rapid rotational change on the y axis.
Is it possible to compare one realtime accelerometer reading against the same variable reading .2 seconds later? Something like:
'if ((euler.y) >= (euler.y)+30);
{
GUI.Label(Rect(150,150,200,150),"high tilt", largeFont);
}'

The later comparison sounds like a standard operation unless I am missing something. Save current value as eg OldValue. Then compare with current value 200 mS later. In a multi function system use eg millis() to determine when 200 ms is up. |One off save: ActionTime = 200 + millis(); Then in loop if (millis() >= ActionTime) { ....}


text:
I want to know how to record and play radio waves?
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?

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

Build a receiver http://www.somerset.net/arm/fm_only_lowtech.html
Tune it to the right frequency
Use it to detect the codes sent from your remote
Build a transmitter http://makezine.com/projects/super-simple-fm-transmitter/
Tune it to the right frequency
Transmit the codes
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.


text:
Temperature sensor reading is higher than the actual temperature
// 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);

What sensor are you using (part no.)?

LM35... @ peter

They suggest a 0.01uF bypass capacitor in the datasheet.

i use it also but still there is no change in reading

Next time please add code to your post instead of in a comment. I've edited your post for now. Thanks!

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

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);
here is the code

@RappySaha
Thanks, I don't see anything wrong with your code. One thought I had was that the lcd.print function accepts only char,byte,int,long, or string. I'm not sure how it will handle TC and TF, if they're of type 'double'. You might want to try casting them to ints lcd.print((int)TF);
As others have said, you could have a bad sensor or a bad connection.
Your math looks right, and your code looks alright.

C++ is supposed to do implicit casting but it can sometimes break, especially with warnings disabled on Arduino. I've had issues with Serial.print() specifically, so that might be the issue.

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.

if i use ds18b20 is the formula will still be same??

There is no formula. The library returns the temperature

@RappySaha more specifically the DS18B20 is a digital sensor. Depending on the library used (or not, I haven't tried them all) you can call a function to return the temperature as a float, representing the temperature in degrees Celsius or Farenheit, or as a int16_t with each single bit representing 1/128th of a degree Celsius. No extra maths is needed.

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;

According to the datasheet, the LM35 is supposed to output 10mV per degree C. Assuming a standard 5V AREF, the formula in the question looks correct (in theory anyway).

You're quite right. Could you post the rest of your code?

I'm not the questioner. :)

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);

"serial.print() needs the number of decimal points" : nope, a default of '2' is included within the function prototype, therefore you can skip the second parameter. The code wouldn't compile if it was needed but omitted.

@CharlieHanson - Yep! Thanks I have corrected my answer.


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

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

Eleventy-seven.

@Ignacio: thanks for that link. Not sure what eleventy-seven means, though. Is it slang for something?

It is a fictional arbitrary number.

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.


text:
Choosing rangefinder for obstacle-avoiding
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..

They are the same. parallax wants /$ for a resistor; http://letsmakerobots.com/node/36885

@Spiked3 they can both be made to communicate with 3 pins, but do they have the same detection characteristics? It doesn't say they are actually the same hardware/mics.

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.

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


text:
Matlab to Arduino communication
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

Consider sending printable values just as if you had typed them into the serial monitor.  It is not the most efficient solution, but it is one of the simplest, avoiding the format-matching and synchronization challenges of multibyte binary data.

I am analyzing images from webcam and continuously sending data to Arduino. I solved the part of sending data, but the problem is that the Serial.Available() is updated only once. It receives much of the data as one string. I need it to be updated after every sending from Matlab. There is no interrupt with each serial fprintf basically.

Communications on the leonardo is packetized, so data will arrive in chunks that may or may not match your initial message size.

Turns out Matlab needed me to define a '\n' terminator in the serial fprintf function along with the type of data to be transferred. The problem was solved, thank you for the help.

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.

you can use all C datatypes available, is this case a short is the better option as it is 2 bytes and matlab can handle it with int16

MATLAB can handle a wide range of numeric data types (see link.) The example code above applies to short (int16) data types just as well, but take note that only two bytes are sent instead of four bytes in the case of float data types.

Trivia: Single precision floating point data is usually referred in C++ as float, whereas in MATLAB it's more commonly referred to as single.

I agree with sentences stated up, but what I was trying to say is that there is no need to use int myVar and then shift it into lower and higher bytes because we can simply use short myVar and Serial.write(myVar). The float part is 100% correct.

Thanks for pointing that out. If the OP only needs integers within the range of -400:400, short would do the job. Clearly, I was too eager to provide a more generic solution to handle multi-types.

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


text:
Send array of Infrared codes
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!

What are you trying to achieve? I don't know what library you're using, but it seems to me that you try to compare if SerChar[0..2] is equal to IDChar[0..2], and send the corresponding code for those that are equal. Maybe you could include a bit more code or an explanation

Well yes I'm comparing those values based on what I receive over serial. Everything works fine. The thing is that it seems I'm not using the correct data type for the IR codes. I'll rephrase my question! Thanks for your concern.

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
        }
      }
    }
}

Great job. P.S. To make your code a bit more intuitive, you could change IRArray = 2 to IRArray = 3, and then use CountIR < IRArray for the loop.

Thanks! I'll hope this could be of some help. I'll edit my response following your advice. Many thanks for pointing that out.


text:
Data at Serial Port Avaliable
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?

You will end up in an infinite loop if you never receive the expected response.  If you are receiving other responses, or noise, you could easily overflow your array, so you should put a hard limit on the growth of x.

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().


text:
Interfacing Arduino Leonardo with PCA8574AN
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();
}

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.) 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!

Hi,If i'm understanding it correctly, the way to go is to write the byte for the LEDs I want activated, then 0x00. I'm just trying to display a static pattern at the moment. `#define TWBR=400000L
#include "Wire.h"
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(0x69);
Wire.write(0x12);
Wire.write(0x00);
Wire.endTransmission();
}` This doesn't work, is it what you meant? Thanks.

@Tim that is what I meant... I must have overlooked something in the code. I'll look at it later tonight if I have time.

@Tim sorry just got time today to look back at it. 1.) the address is 0x70, not 0x69. 2.) The only other thing that I can think of is, in the examples, they always send the data to 0x0 and then the first byte is the address (0x70). 3.) Ignore the advice in my post about the last bit being a 0: that just is supposed to shut it off... right! Further than that I don't have a lot of other ideas.

@Tim did you fix it? What fixed it?

Haven't yet.  Will try again today.


text:
Unable to alter SPI speed on Arduino Micro
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.

What data type is the variable m_SPISpeed?

@RogerRowland, unsigned int

If that's a Uno, then unsigned int is only 2 bytes, so max 65536. Which Arduino?

Try unsigned long m_SPISpeed = 400000L;

Its a Arduino Micro, i have to try again tommorow. But i am afraid that you may be right!

Strange. I tried to change it to unsigned long, but now it is maxing at 250kHz. I tried to type 400000L directly in the settings and this is still the maximum i can reach. Is there another parameter i need to change?

Put another zero in that literal, 4000000L, looking at the source code for the new SPI library, it applies a simple algorithm to get a clock divider, so unless you're spot on with a multiple, you get the next lowest.

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).


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

FYI, PWM doesn't vary voltage at all except going to Vcc and Gnd. It's never in between.

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

Or a little less, depending on load.  In effect, the PWM maximum at 100% duty cycle is VOH or the high-state logic output voltage, and the data sheet will characterize what that is in relation to Vcc.

The datasheet itself does not specify a maximum in the tables, but in the charts it gives a maximum of Vcc.

There's a difference between "Maximum that could be seen" (which arguably is more like Vcc+.6v) and "Voltage that will be seen at Maximum duty cycle" - the latter is the same as the voltage of a "1", and that is not necessarily Vcc but rather depends on the load, in a way that the data sheet should at least roughly characterize (ie, voltage at a given source current, effective Rdson, etc).

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).

+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.

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