text:
Arduino Pro Micro clone not recognized, flickering RX LED
I have an Arduino Pro Micro clone that seems to be in some sort of reset loop. The RX LED is flickering very fast and very dim. The power LED also seems to flicker at the same frequency but has normal brightness.
The Arduino is not recognized by the PC at all anymore. It was working fine before. It doesn't matter if I try to go into the bootloader, by pressing reset twice, or not. Nothing happens. It feels like it is constantly resetting. The flickering stops if the reset pin stays connected to GND.
Another clone from the same shipment is still working fine. Both running the blink sketch. Just this one started to malfunction all of the sudden - after probing the pin I set in the blink sketch with my multimeter to see if the flashing was a success.

See if it's bricked. I put this on YouTube last month http://youtu.be/RZH_qGautqM

It's an Atmel with USB onboard, not usb to serial chip in between.

I've heard of a fix where you hold down the reset button until right before the Arduino uploads. The goal is to catch it in the bootloader state before it starts the sketch. You might need to try it a few times...

Well the PC doesn't even recognize it so I can't upload anything.

When  you say the PC doesn't recognise it, do you mean that you get the USB device not recognised message in the system tray, or do you get nothing at all on the PC end, if you hit reset for example?

Nothing at all. Windows sees nothing connected to the usb cable.

But, can't you use other Arduino or FDTI USB brick to upload code via serial link (I'm talking from distant memory.) i.e. to use the method you would otherwise use to upload Arduinos having no usb port (like Mini)

It has native USB, it doesn't recieve code via UART

If your pro micro does not have a reset button, wire one between reset and ground.
Press reset twice, quickly, and immediately hit upload on the IDE.
Secondly, make sure you've downloaded and installed the Sparkfun board files for the pro micro.

I can't upload anything as the board is not recognized in Windows. Doesn't matter in which mode the board is in.

You've installed he Sparkfun boards as well?

Yes but that wouldn't make a difference, thats just description files. The problem ist that the serial device is not coming up at all. The usb communication part is completely dead.

+1 for the Sparkfun Pro Micro board files. I did wonder why the board wasn't listed in the Board menu.

This is a very common problem. See my answer to Arduino Micro just blinks, won't connect to PC.
As Asenkhan says in his answer, it is often caused by attempting to upload to a Pro Micro using the wrong board setting 3.3 V en lieu of 5V, or vice versa.

I have written two lengthy blogs about the whole experience:

The case of the broken Pro Micro
The case of the broken Pro Micro (reprise)

This does help but unfortunately not for this one. I could revive another Pro Micro that I programmed with the wrong settings using that method but in this case, no matter how often I try, it does not go into bootloader mode. I have the feeling something is causing it to constantly reset, hence the flickering that only stops when I keep the reset pin connected to GND.

@ProfessorSparkles - Hmmm, that does sound unusual. Sorry, that I couldn't help.

Try this: unplug the Arduino, hold down the reset button, and then plug it in to power. Hold down the reset button a few seconds after you power it on. If this works, you should get the "blink" sketch, and be able to reprogram it.
Alternatively, if you have an ICSP programmer (I use the FreeTronics USBASP), plug this in (you will need to wire up the appropriate 6 pins), and then use the Arduino IDE to burn the bootloader - select the board, serial port, and programmer,then select "burn bootloader" - all from the "Tools" pull-down menu.

The holding of the reset button down doesn't seem to work for me. Do I keep it held down during the uploading? If not, at which point should I release the reset button? I'm going to have to resort to using my USBasp I think. Also, for a Pro Micro 3.3V, I will need to reduce the voltage levels, I guess. The USBasp => Pro Micro connections are as follows: MOSI = 16, MISO = 14, SCLK = 15, RESET => RST, plus Vcc and GND obviously.

Try this:

Connect a push button switch to ground and reset (RST) pin;
Click upload then push the button twice (fast) = it doesn't matter if your computer does not recognize the pro micro;
Repeat this if it failed (repeat until you are successful).

After this the Pro Micro port will comeback to life.
I tested it. The reason I think that you bricked it, is because you uploaded using the wrong board setting - commonly the 3.3 V and 5 V (or vice versa)

I bricked my Pro-Micro within ten minutes of ripping it out the packet. I didn't realise that (a) it's not so brilliant on USB 3.0 - or in my case, unuseable, and (b) it's not actually an Arduino board - the Pro-Micro is a SparkFun product, and any clones thereof are from SparkFun's schematics.
The latter was only a problem to begin with, while I was scrabbling around on the Arduino website in vain trying to find answers. Once I realised to visit SF's website everything calmed down. Read this section on bricked/unrecognised pro-micros, and then have a look at the rest of the page as further reading.

Tried that but unfortunately the Pro Micro doesn't stay in bootloader mode nor does it ever connect to the PC when trying that double click reset.

+1 for the link, very informative. I have the same issue, a bricked Pro Micro. All three LEDs are lit (Rx, Tx and Power). I can get mine into the 8 seconds bootloader mode, but the IDE won't upload Blink on to it.

You can make it work but only if you use a ISP programmer and burn the bootloader. The internal serial programmer would not work still some HID functions are retained. To me everything works fine except the Mouse functionality.
This a pain in the acc* but it will work for other options. The other thing I have not tried is setting an old arduino ide and use the old addon for pro micro board to see if there a was a change in those files that caused it to fail.
So my next step would be as follow:

Setup the old arduino environment, download the old addon files and burn the bootloader.

Edit: While writting my findings I came with the solution. Just as I thought! You need to use the old files to make this work completely.
Steps:
You'll need to buy an ISP Programmer for burning the bootloader or use another arduino board as an ISP Programmer
I used the USBtinyISP Programmer. In specific:

Download the old sparkfun files (zip) version
Sparkfun Old Addon Files
Download the old Arduino IDE - I used the 1.0.6 portable (zip) version
[Old Release Files] (https://www.arduino.cc/en/Main/OldSoftwareReleases#previous)
Extract the Arduino IDE to Desktop. After doing so open the Sparkfun addon zip file and extract it to the Desktop. Then rename the extracted folder from:

SF32u4_boards-pre-1.6

To

sparkfun

Alright copy that folder and if you do as I mentioned above now you'll head for the Arduino IDE we just downloaded. When you see the arduino files move into the hardware folder and paste the sparkfun folder inside of it (don't navigate any further than this).
Then connect the ISP following this diagram: Always double check the connections!

Now the next steps would be:

Open the Arduino IDE v1.0.6
Select your programmer under Tools (mine was USBtinyISP)
Select your Sparkfun Pro Micro board either the 3.3v or 5v version
Now under Tools select Burn Bootloader

If you do this right after a couple of seconds or minutes you will see a message that the process of burning the bootloader was completed. Depending on your hardware speed, if you store things in a flash drive or system is running on a linux live session you will need to wait a bit so just relax.
If things go according to plan then you can disconnect the ISP programmer and upload a simple sketch to corroborate the board is now working.
int ledPin=10; // let to pin 10

void setup() {
   pinMode(ledPin, OUTPUT);
}

void loop() {
   digitalWrite(ledPin, HIGH);
   delay(1000/2); // 1/2 a second
   digitalWrite(ledPin, LOW);
}

Upload as you normally would! Double check the board version!!
Perfecto! If the steps were followed in order you'll now have a working device

It can be problem with bootloader.
You can try to burn bootloader again.
See for example:
http://angryelectron.com/how-to-update-the-bootloader-on-arduino-pro-mini-328/
Or use google

-1 Because it's a Pro-Micro - with an ATmega32u4.


text:
Sending string over serial to nodejs app. Why does it get chunked?
I'm sending a string from my sketch over Serial port as follows:
Serial.println(F("Found ILI9341 LCD driver"));

On the other side, I have a nodejs app using the serialport npm module, with something like this:
var SerialPort = require('serialport')
var serialPort = new SerialPort('/dev/ttyACM1', {
  baudrate: 9600
})

// it opens the connection and register an event 'data'
serialPort.on('open', function () {
  console.log('Communication is on!')
})

// when your app receives data, this event is fired
// so you can capture the data and do what you need
serialPort.on('data', function (data) {
  console.log('data received: ' + data)
})

Communication works, but on nodejs side I get the output chunked, as if it had line breaks, like this:
Communication is on!
data received: Pa
data received: int!
data received:

data received: Fou
data received: nd I
data received: LI93
data received: 41 L
data received: CD d
data received: rive
data received: r

Why does this happen?

It seems I needed to add a parser to SerialPort nodejs module, in order to specify how the input should be treated.
I changed my code to this:
var SerialPort = require('serialport')
var Readline = SerialPort.parsers.Readline

var serialPort = new SerialPort('/dev/ttyACM0', {
  baudrate: 9600
})

var parser = new Readline()
serialPort.pipe(parser)
parser.on('data', function (data) {
  console.log('data received: ' + data)
})

serialPort.on('open', function () {
  console.log('Communication is on!')
})

Basically, I'm specifying a Readline parser, which matches with the Serial.println function calls on my arduino sketch. Now the console output works as expected:
Communication is on!
data received: Found ILI9341 LCD driver

You do not need to pipe(): you can new SerialPort('/dev/ttyACM0', { baudrate: 9600, parser: Readline("\r\n") }).

@EdgarBonet I'm not sure about that, because according to https://www.npmjs.com/package/serialport#module_serialport--SerialPort.parsers you need to register for the 'data' event in the parser, not the port, so you need the reference to the parser to do a parser.on('data', yourFunction). Recommended usage seems to be using pipe().

You are right. I was using an older version of the serialport module that doesn't work in the same way. Sorry for the confusion.

source: Stack Exchange

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

sort: votes


text:
Confusion about PNP transistors
I was reading through SparkFun's article on transistors when I came across something that confused me. The article showed this circuit:
With this description:

Similar to the NPN circuit, the base is our input, and the emitter is tied to a constant voltage. This time however, the emitter is tied high, and the load is connected to the transistor on the ground side.
This circuit works just as well as the NPN-based switch, but there’s one huge difference: to turn the load “on” the base must be low. This can cause complications, especially if the load’s high voltage (VCC in this picture) is higher than our control input’s high voltage. For example, this circuit wouldn’t work if you were trying to use a 5V-operating Arduino to switch on a 12V motor. In that case it’d be impossible to turn the switch off because VB would always be less than VE.

I am confused because the part about the Arduino not being able to turn off a PNP transistor makes sense, but doesn't the circuit shown feature exactly the situation described that the transistor wouldn't work in? Is this an oversight by me and is there something else going on here that I don't understand, or is this a mistake in the article?

"this circuit wouldn’t work"

That's what I'd think, but this is what was shown on the article....

I pulled that text from the posted description verbatim.

.... For example, this circuit wouldn’t work if you were trying to use a 5V-operating Arduino to switch on a 12V motor. ....

Don't actually do this to your arduino. The 12v will damage your arduino, especially when the 5V state is meant to output voltage, not taking in the 7v difference from the 12v.

I explained all this in the answer to your other PNP question. If you choose not to believe me then that's fine...

@Majenko ehehe funny thing, he wasn't the OP of the other question, he was the answerer to the other question.

@Bradman175 So he is. It was late and I'd spent the evening singing in Welsh, so my brain wasn't firing on all cylinders.

The article is saying that the circuit wouldn't work, thus it illustrates (correctly) something that won't work. What is the confusion?
To turn the PNP transistor off, the base voltage needs to be low with reference to the emitter voltage. Thus with an emitter voltage of 12V, and the most the Arduino can output is 5V, the transistor will never be off.

Sorry learner comment here. I tried it on a bread board with 3.3 and 5v interestingly applying either +3.3 or gnd turned it on and floating was off? 1k resiter to base. I thought you could never turn it off. I must be missing somthing?

I'm not sure what you mean by "floating was off". Perhaps you should make a new question and reference this one if needed.

@AndrewT  As a general rule applying a floating input will result in undefined behaviour. With floating input there might be leakage from other parts of the circuit, enough to produce behaviour you are not expecting.

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

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


text:
Arduino Connect Long Wires/Cables
i am completely new to hardware programming and micro controllers and i am unable to figure out what search-engine search-term to use to find the answer i am looking for.
the project
i am working on a project that will use an arduino to control the opening and closing of a window; in a shed. the project i am trying to achieve is further described here.
the question
i want to know what are the limitations of wire length in an arduino project and what do i need to have to be able to extend that wire length capacity?
i currently have those "common" 20cm wires you get off ebay... which i dont think will be long enough.

If 20 cm is not long enough, what is long enough then? 2 m, 200 m, 20 km?

for this example lets say 3m... i plan the window to be on the roof... i figure my options are to either "stick" the arduino on a wall nearby or have long cables to the floor. i think the second option better achieves safety for the arduino because i could put the arduino inside some waterproof box on the floor.
i dont expect it to get wet inside... but i cant guarantee that.

What kind of motor are you going to use to open and close the window? What type and voltage? The distance will depend on that.

i dont mean to advertise amazon products or anything... but something like this is a type of motor  that seems easy to control... (i have micro servo SG90 working as expected. my expectation is that the large one will work similarly (of course with more power requirements))... i do not think the window will be too heavy... but this motor seems sufficient... perhaps my expectation here are too optimistic. feel free to advise on anything you think i may not have considered.

The stepper motor 28byj-48 seems to be a 5V motor (datasheet). I've seen it being used with a A3967 driver, which means that it does not draw more than 750 mA of current.
I'll go with the length you mentioned in the comments:

for this example lets say 3m

The rest is Physics: the resistance of a wire is
R = p * l/A

where l is the length of the wire and A is the area (dependent on the diameter).
A voltage drop calculator can now tell you how much voltage is left at the end of the wire.
I would have estimated a 0.75 mm² (AWG 18), but you might even be fine with 0.5mm² (AWG 20) according to the calculator. But: better safe than sorry.

Also from the comments:

i have micro servo SG90 working as expected. my expectation is that the large one will work similarly (of course with more power requirements)

A stepper motor needs a totally different setup than a servo. The servo is connected with simple 4 pins, the stepper needs a motor driver (H-bridge). Connecting the stepper motor directly to the Arduino may destroy your board.

thanks for you reply... i have decided to not use the stepper as described in a previous post. i think the mechanical requirements are simpler with the use if a servo motor because i do not need continuous rotation to open a window and i have a working proof of concept working with cheap SG90 servo you can get with some "cheap" arduino kit.

@X0r0N: be aware: the SG90 can hold ~1 kg in 1 cm distance, 100 g in 10 cm distance and 10 g in 1 m distance. You'll need a much more powerful servo.

i think so too... my plan is to use this one or similar.

Wire length is hard to define. It depends if it is in your case powering a motor or has control signals connected directly to the Arduino. Take a good look at the answer provided by Thomas Weller, by sizing the wire appropriately you can get extremely long lines for motors and other types of loads, you have some voltage to work with. The wires connected to the Arduino are also antennas and can pick up a lot of nasties in a very short run, especially around motors. These antennas on the inputs are high impedance making them more sensitive to noise. Regardless of which wires you are looking at they need to be properly conditioned for your environment and application.

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


text:
How can you export data to a file in Arduino?
How can I export the readings that are being sent to my Arduino Mega to a file?
I know there is a write() method but I can't find the documentation on how to use it.
I want the file to be created and stored on my PC not an SD card. Also I want to know if there is a way to do this without using external programs.

Where do you want this file to be? On an SD card or on your PC?

You can use a terminal program like putty or Minicom to write that data to a log file. Then you can use whatever program or app to process this log file.
Both programs can read from the serial interface.

if your arduino is connected to a computer, you can create a small application that will listen to serial port and write on a file whatever arduino sends over the serial.
Alternatively you can write directly on an sdCard. (There are many sdCard shields available on the market.)
As for the write method, you probably are referring to write method of File class of SD library

Isn't there a way of doing this without having to use another program?

@IsabelAlphonse Use the serial terminal built into the Arduino IDE. And copy/paste the text from it into a text file ;)
There isn't really a way to get stuff done on a PC, withouth a program ;D

I know there is a write() method but I can't find the documentation on how to use it.

You can use: Serial.write(F("TEXT")); to send text over the "serial communication".
This basically means that your Arduino will send the text to your PC over the USB emulated COM port.
The magnifying glass button at the top-right of your Arduino IDE's screen will open the "Serial Monitor" here you can see the text that's coming from the Arduino, you can even send text back.

How can I export the readings that are being sent to my Arduino Mega to a file?

You could make your Arduino interface with an SD-card.
Or use that serial connection I told you about.
You could create a program (on the PC) that takes the serial input and stores it into a file. A lot of examples from this should be on the internet.
Another thing might be, to use a more advanced serial terminal. I believe "terminal.exe" allows "logging" to a file.


text:
Can you access the EEPROM of an ATtiny with Arduino Code?
I'm attempting to reduce the amount of RAM being used by my program by writing some values to the EEPROM of my micro controller. I'm currently programming on the ATtiny85 which has 512 Bytes of EEPROM. According to the documentation this is how you write to EEPROM:
#include <EEPROM.h>

void setup() {
  EEPROM.write(0, 1);
  EEPROM.write(1, 0);
  EEPROM.write(2, 3);
  EEPROM.write(3, 2);
  EEPROM.write(4, 1);

}

For some reason this isn't working for me and I can't seem to find the error. Am I programming this wrong or can the EEPROM of the ATtiny simply NOT be accessed with Arduino Code?
Here is the Datasheet: http://www.atmel.com/Images/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet-Summary.pdf
Here is the second sketch I'm using to test the EEPROM:
    #include <EEPROM.h>

void setup() {
  EEPROM.write(0, 1);
  EEPROM.write(1, 0);
  EEPROM.write(2, A3);
  EEPROM.write(3, A2);
  EEPROM.write(4, A1);

byte CLK = EEPROM.read(0);

}

void loop() {

  if(CLK == 1)
  {
    for(int i = 0; i < 3; i++)
    {
    digitalWrite(0, HIGH);
    delay(1000);
    digitalWrite(0, LOW);
    delay(1000);
    }
    exit(0);
  }
  else
  {
    for(int i = 0; i < 100; i++)
    {
    digitalWrite(0, HIGH);
    delay(1000);
    digitalWrite(0, LOW);
    delay(1000);
    }
    exit(0);
  }

  exit(0);

}

I wish I had the ATTiny you have with 512MB of EEPROM, it must be a new one. Please have a look at this http://arduino.stackexchange.com/help/how-to-ask

What is wrong with my question?

an ATTiny has 512 bytes of EEPROM and you also asked a similar question earlier. You need to add what you have tried to retrieve those values and how you know they have been retrieved properly. The eeprom values have been written to properly in the above 'snippet'. And that's the problem you have not given all your code.

I didn't write the other EEPROM question. I saw that it was unanswered and decided to ask my own. Also, my question is about the ability of the ATtiny EEPROM to be programmed with Arduino. Like I said, my code was working fine until I switched the value with EEPROM.read(0) which caused the code to just stop working.

the ATTiny can be used with the EEPROM library from the arduino ide it is basically a wrapper of the avr/eeprom.h. What also might kill your first cell in EEPROM is repeatedly reading it in the loop. That kills EEPROM cells, they have limited read write cycles. Also why do you have exit(0)

Thank you, that's some great information. Follow up question: If I write on sketch with the write commands can I then access those values using another sketch? In other words can I split my program up the way I just did in my question?

please would you stop changing the code in the question.

Sorry, I tried to improve it based on your feedback. However, I understand what you're trying to say so thank you I think I can figure it out from here.

okay. I am editing my answer with a bit more stuff please have a look at it.

Move the definition of byte CLK = 0; outside void setup and then do this in void setup:  CLK = EEPROM.read(0);

Problem is that if I set the value of CLK inside the function method I can't access it in any of the other functions.

Here is the second sketch I'm using to test the EEPROM: - no it isn't because that doesn't compile:
sketch_jun22a:16: error: 'CLK' was not declared in this scope

The Arduino EEPROM library is compatible with the ATTiny range of AVR microcontrollers as the library itself is built on the standard Atmel AVR avr/eeprom.h 'library' so it is compatible with all the AVR microcontrollers.
The EEPROM also doesn't take to being written or read to often as EEPROM can wear very quickly. Reading though does not cause much damage though.
Also note that using exit(0); will stop the ATTiny from doing anything else after it is called so I hope your intention is to only run the loop once, if not this would account for either not seeing anything or it only ever running the blinking cycle once.
To answer your follow up question. Yes you can run one sketch to set you values in EEPROM and then use another sketch to read those. That us usually the point of EEPROM it is a memory type that "keeps its value while there is no power".
Also you need to make sure the ATTiny is set to preserve EEPROM during upload with the ISP, this is done with the fuse settings. You need to look for a tutorial on fuse calculators for the AVRs. To set the EESAVE you need to set the High fuse to 0xD7, you can change this in the boards.txt file. Here is a fuse calculator.
If the code that is on your question at the moment is being used you won't be seeing anything as it needs the pins to be set with pinMode. That's a note for others that see this.
Next what you can do is run a basic test code which blinks the LED without anything else going on.
Basically:
void setup(){

 pinMode(0, OUTPUT);

}

void loop(){

 digitalWrite(0, HIGH);
 delay(1000);
 digitalWrite(0, LOW);
 delay(1000);

}

Below is the code you have written, it works I have it running in front of me.
I have commented it and changed a few things to make it work as intended, although the intention is not clear.
#include <EEPROM.h>

byte CLK = 0; //This is a global variable with an initial value

void setup() {
  // put your setup code here, to run once:

  EEPROM.write(0, 1); //set the pin to D1
  delay(5);

  //read from EEPROM address 0
  //this sets the value of the global variable CLK
  CLK = EEPROM.read(0); //place this inside a function

  //just to give an example...
  byte PIN = CLK;   //PIN variable is a local variable

  pinMode(PIN ,OUTPUT); //using that local variable

}

void loop() {
  // put your main code here, to run repeatedly:

  // Note: the below if() will always be true as the value
  // of CLK is never change and shouldn't be changed as
  // it will change the pin number of the output

  if (CLK == 1) {
    for (int a = 0; a < 3; a++) {
      digitalWrite(CLK, HIGH);  //this uses the global variable
      delay(1000);
      digitalWrite(CLK, LOW);
      delay(1000);
    }
    //putting exit(0); will actually stop the program
    //remove it
//    exit(0);
  }
  else {
    for (int a = 0; a < 100; a++) {
      digitalWrite(0, HIGH);  //this has a predefined pin no.
      delay(500);
      digitalWrite(0, LOW);   //this has a predefined pin no.
      delay(500);
    }
    //putting exit(0); will actually stop the program
    //remove it
//    exit(0);
  }
}

Thanks, it works. My problem now is that I can only use EEPROM.write(); inside of a function and that prevents me from creating a global variable that all my function can use.

@IsabelAlphonse   ??. The EEPROM.write() is a function and has to be used within a function. I think you need to start with the basics TBH. What I also think you mean is the read part. I have edited my answer to include the code you have written that works.

@IsabelAlphonse  please can you mark one of the answers as accepted so that the StackExchange system doesn't bump it up in a few weeks and also to allow others to find it more easily when searching for the same problem.

Sorry, I forgot.

You said: "The EEPROM also doesn't take to being written or read to often as EEPROM can wear very quickly. "
Datasheet says:
Memory Flash Endurance: 10,000 Write/Erase Cycles,
EEPROM Endurance: 100,000 Write/Erase Cycles. So EEPROM can be written ten times more often than the flash memory.

@needfulthing The data sheet does say that (I stand to be corrected but I do believe it's per each address, hence improving life of eprom is done with wear-leveling), but when most people go crazy writing to one address of the eeprom it does wear quicker than you would wear out the flash. Most use it as more of a dynamic storage when the device is running, or for settings. While the flash may never reach the amount of read/erase cycles of the flash once made. I just bear the fact of it wearing in mind when making something.

@RSM Ah sure, absolutely true in that aspect.

When you upload a new sketch with the default settings, the EEPROM will be cleared.
"The -e option instructs avrdude to perform a chip-erase before programming; this is almost always necessary before programming the flash."
If you're using the Arduino IDE, the -e option is enabled by default. This is probably why it's not working for you.
See also the question Is there a way to preserve EEPROM contents in AVR Atmega when burning a new firmware to flash with avrdude?

Then my test code should be working at least. I write to the EEPROM in the setup method and set the CLK variable afterwards. But when I enter the loop() method I still can't get my light to blink.

It is now very common to read from EEPROM in an ATTiny, particularly an OSCCAL value. It has also been the case for some embedded devices to perform a superfluous write and read back to external EEPROM during POST. Every boot.
> ---snip---
>     current tick:1 sec
>     EEPROM Init...
>     Write EE_TEST ==0x7cf u8EEData1=0xaa
>     Read EE_TEST ==0x7cf u8EEData1=0xaa
>     [EEPROM 24c16 found!]
>     EEPROM: Data valid
>     Restore Configuration from EEPROM to Device...
>     Show MY MAC Address(from 24c16): (0x00:92:58:01:45:4d)
>     _24c16_eeprom_word_read: EE_DHCPEN: (01)
> --- end snip ---

In addition, available cores include options to suppress EEPROM erase in programming, this is fuseable.
In ancient times AVRDUDE would write flash counts to the four bytes terminated by E2END. (the -y option).
You need to include the header.  You can check, peek and poke, the contents with a sketch or by using avrdude in terminal mode (-t) with "dump ee".
And yes, it is normal for Arduino work to have a dedicated temporary sketch to load EEPROM data.
So SRAM (or FLASH) does not matter, there is a lot of FLASH compared to EEPROM.
Keep it simple and test your results. Depending upon the library or core, it is best to avoid crossing page boundaries as addressing may wrap around to the beginning of the page due to 6 bit truncation as for I2C external EEPROM. Don't trust, verify.

Is that boot time write intended to be for planned obsolescence or just bad coding practice.  If you want to check for the function of storage you could leave a couple byte signature that you read out instead of stressing the EEPROM (internal or external) with regular pointless writes.

It was bad coding. I think it was just left in the script from development. Netgear if it helps.

Not sure if things have changed so significantly since the question was asked originally but I'll answer using the Atmel AVR libraries.
Don't assign the EEPROM value to a variable as then you are wasting precious SRAM again. EEPROM has unlimited read cycles.
I can't find any current references to EEPROM.read() as a Macro or function in the Arduino IDE. Instead there is the AVR EEPROM library which uses eeprom_read_byte() as shown below.
#include  <avr/eeprom.h>

// the setup routine runs once when you press reset:
void setup() {
/* The "131" value is used to prevent damaging excess EEPROM writes on every restart.
   If you want to try setting a different GPIO pin for LED blink change the test value in
   both the read and following write to EEPROM address 511 */

    if (eeprom_read_byte((uint8_t*)511) != 131) {
       eeprom_write_byte((uint8_t*)511,131);
// Store the GPIO pin number in EEPROM address 1
       eeprom_write_byte((uint8_t*)1,1);
    };
// initialize the digital pin as an output.
    pinMode(eeprom_read_byte((uint8_t*)1), OUTPUT); // LED pin value stored in EEPROM address 1
}

// the loop routine runs over and over again forever:

void loop() {
    digitalWrite(eeprom_read_byte((uint8_t*)1), HIGH);
    delay(1000);               // wait for a second
    digitalWrite(eeprom_read_byte((uint8_t*)1), LOW);

    delay(1000);               // wait for a second
}

For reference, Arduino has a EEPROM library as part of its ecosystem. https://www.arduino.cc/en/Reference/EEPROM

maybe the reference is there but in Arduino IDE 1.8.5 I am using here if I try and use #include <EEPROM.H> I get a compilation error which is why I posted the working source code I did. C:\Windows\Users1\Users\WINDOWS\AppData\Local\Temp\arduino_modified_sketch_177973\sketch_oct24a.ino:1:20: fatal error: EEPROM.h: No such file or directory


text:
Understanding types of timer interrupts
I'm learning this note about timer's api on Arduino Due. Interrupt can be attached with the next function:
void tc_enable_interrupt(
       Tc * p_tc,
       uint32_t ul_channel,
       uint32_t ul_sources)

Where the input parameter ul_sources can be one or more of the following:

TC_IER_COVFS Enables the Counter Overflow Interrupt
TC_IER_LOVRS Enables the Load Overrun Interrupt
TC_IER_CPAS  Enables the RA Compare Interrupt
TC_IER_CPBS  Enables the RB Compare Interrupt
TC_IER_CPCS  Enables the RC Compare Interrupt
TC_IER_LDRAS Enables the RA Load Interrupt
TC_IER_LDRBS Enables the RB Load Interrupt
TC_IER_ETRGS Enables the External Trigger Interrupt

I'm more like mobile developer and I don't understand what does all this interrupt types mean.

The datasheet is a good place to start, http://www.atmel.com/images/atmel-11057-32-bit-cortex-m3-microcontroller-sam3x-sam3a_datasheet.pdf, See chap. 36. Timer Counter (TC), pp. 856 and forward. It is really simple. Just a counter and a few registers to match counter value.

@MikaelPatel, this chapter is to difficult for me.

At least take a look at Figure 36-6. Waveform Mode, pp. 866. It shows the interrupt flags and where they come from. A Timer is basically a counter with a clock source and a few match/load registers. Interrupts are typically when the counter comes to a specific value such as overflow, contents of A/B match register, etc. It is not rocket science.

@MikaelPatel, ok thanks. I will take a look. Actually I want to achieve one of this things: A) Timer Interrupt that fires only once; B) Adjustable timer interrupt, so I can modify phase without restarting the timer.

A) disable the timer interrupt in the ISR, B) adjust the match register in the ISR, are typical methods. Typical ISRs can be found in for instance Cosa Real-Time Timer (RTT) implementation, https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/RTT.cpp#L143, Compare A is used for millis-seconds count update, Compare B is used for one-shot micro-seconds level job scheduling.

Thank you. I've thought about disabling interrupt in the ISR but it seem to expensive by performance to me.


text:
Arduino does not work
When I try to upload a sketch to my Arduino Uno R3 then sometimes I get the following issue:
At the beginning the RX LED flashes three times and then I get errors:
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xd1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xd1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xd1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xd1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xd1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xd1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xd1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xd1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xd1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xd1

Sometimes I get this:
    avrdude: ser_open(): can't open device "\\.\COM3": Odmowa dostępu.

And sometimes Windows does not see the Arduino.
At this site Have I bricked my Arduino Uno? Problems with uploading to board I read that to check the programmer I must to connect RX with TX and GND with RESET pins and then plug Arduino to my computer, open Serial Monitor and write anything and if you receive the same characters from the Arduino, then the programmer and USB cable are OK. It worked for me.
And I have got one more info. When I plug Arduino with USB to my laptop the L led lights. When I press Reset on Arduino nothing happens, it still lights.
I recently bought a new USB cable, and it worked one day and then I could not upload sketches again. I uninstalled and installed drivers, but nothing changed.
This is a short video with my Arduino https://drive.google.com/file/d/0ByeWvrEgy2gRbWdHQ3d5RWU3Mmc/view?usp=sharing

I will buy USBasp programator is it a good idea?

I am not sure about that particular error. But, have you set the right board and port on the arduino IDE?

Yes i checked it and I have right board and com port, but thanks for comment.

Restart your PC, "Access denied" is because something/some program is using your COM port. Or might have not been closed correctly by another upload or program.

It's normal that the L-LED is steady on after the USB connection is established. However, after pressing and releasing Reset it should flicker for a second, then go back to on again.
Check https://www.arduino.cc/en/Guide/Troubleshooting#toc1 for reasons why you can't upload.
On http://www.arduino.org/products/boards/4-arduino-boards/arduino-uno I've found:

The Arduino Uno has a resettable polyfuse that protects your computer's USB ports from shorts and overcurrent. Although most computers provide their own internal protection, the fuse provides an extra layer of protection. If more than 500 mA is applied to the USB port, the fuse will automatically break the connection until the short or overload is removed.

I haven't found out so far, how to read the current values of the fuses.

I will buy USBasp programator is it a good idea?

But when I click reset the l-led is not flicker

From the first link: Make sure there's a bootloader burned on your Arduino board. To check, reset the board. The built-in L LED (which is connected to pin 13) should blink. If it doesn't, there may not be a bootloader on your board.

@JanOkoński If you have no other Arduinos then yes, it's always a good idea to have a USBasp programmer. Make sure you get the one with 3.3V/5V mode, USBasp itself programming jumper and the right cable to program regular Arduinos. (http://g01.a.alicdn.com/kf/HTB1PB8pKpXXXXc3XVXXq6xXFXXXz/AVR-USBASP-Programmer-ATMEGA-ATMEL-downloader.jpg) Should cost just as much, but has much more features.

Serial could be flooded if you were spamming it in ur last program you uploaded.
Ur arduino is broken
Try reflashing ur bootloader which is a common problem when you see data sync errors.

I will buy USBasp programator is it a good idea?

Yes, buy the USBasp programmer, reflash the bootloader with it, and try uploading code again. A corrupted bootloader very well may be the problem.

authors: Дмитрий Шевчук


text:
integration of GSM module and Bluetooth using arduino
Please help me. There is a conflict when I put GSM and Bluetooth module in one MCU. The problem is when I use the GSM, the Bluetooth will not respond and vice-versa.

How do you "use the GSM" and what response are you expecting from the Bluetooth module that you didn't get? There's not enough information here to know what's happening.

actually i cant connect the GSM module to the network and also i cant combine the GSM module and Bluetooth module in one MCU. i'm using arduino uno


text:
Communicating between a computer and multiple Arduinos
I am designing a experiment of controlling 6 small wind turbines wirelessly. For each wind turbine, I need to measure power time series (or voltage or current time series) from the generator, and control blade pitch angle, yaw angle, and generator load (using variable resistance). The control input will be all PWM signal.
I am planning to put an Arduino UNO with a ZigBee wireless module to each wind turbine, making it measure the power time series and transmit to the central node, as well as receive the control input from the central node and command the control input to servo motors. The central node will be additional Arduino UNO.
Here are my questions:

Is it possible for each Arduino to send time series signal to central node wirelessly without interference with other Arduino? (6 wind turbines transmitting time series to a central server). If it is possible, How can I implement such network ? recommending a source for learning would be also greatly helpful.
Interface between the central node and the computer software: The algorithm in the computer need to process the received power time series and determine the optimum control input for 6 wind turbines. Then these control input should be transmitted to wirelessly to 6 wind turbines. In such case, what is the good option to interface the algorithm and the Arduino connected to the computer? Currently the algorithm is written in Matlab. I heard there is the sketch interfacing Arduino and Matlab, is it efficient enough for such project?

It is very interesting project. In my opinion, i would not do like you want to control generators from one point.

Look at ZigBee and Wireless sensor network. It is possible. Do more search, also there are several books about networking.
I think that would be more efficient to control the wind turbine with an Arduino and send only data to the main computer. Main computer should do some calculations or send some main configuration data or control on/off wind turbine basis of:
2.1  Metrological data (wind speed or else);
2.2 Storage SOC(if you will store it in batteries or somewhere);
2.3 Required power of grid and etc. etc.

Arduino UNO like you said, connected to computer could do just data collection and making it compatible with computer(MatLab or whatever) and spread control data from PC to targeted Arduino.
Added links
Could not add more than 2 links due to low reputation :)
http://www.digi.com/pdf/wp_zigbeevsdigimesh.pdf , http://forum.arduino.cc/index.php?topic=105273.0

In such a case I would use HTTP requests from a web server using PHP to arduino.
In a simple explanation the PHP sends a string in its url and then the arduino checks for that string and do something.
I have used such method and it served me well and actually fast too.

I have done a similar project in the past;
for simplicity's sake, lets call the 6 arduino's + turbines "Endnode" and the central receiving and sending arduino the "Controller"
The general idea is that each endnode periodically sends a zigbee package(it's important that it is an actual zigbee package, do some research on this subject) to the controller.
The controller can receive these packages in the form of a serial interrupt. that way, whenever a package is send, the controller instantly starts to handle it.
The controller can send the data to the computer, I recommend using http transfer, as it's easy and probably fast enough.
This proces can be reversed in order to send a command to the endnodes to control the turbine.
If you're interested in my previous work on this subject, I reccomend you check out:
Libraries of my previous work
And
The sketch used for the project
I appologize for any weirdness, as it was a student project. But it worked flawless ;)
Good Luck!

From experience my recommendation would be to use Arduino nanos and NRF24L01 modules, using this library: http://tmrh20.github.io/RF24/
Use nanos for monitoring and one for acting as host. I presume you are comfortable writing a vb.net app or similar for reading the host serial data via usb?
Quite simply, your six monitors will await signals addressed to them. Depending on that signal, they can either transmit their current data, or change turbine settings, etc.
With clever coding you can avoid multiple arduinos attempting to transmit simultaneously, and avoid any interference issues.
Good luck, drop me a line for more info if needed. Using nano clones and pack of NRF24L01 modules for < $10 you'll be able to set this experiment up very cheaply - aside from the turbines!


text:
split reading sensors values from stream after it via xbee
I'm trying to make project to monitor my home. I am using some gas sensors and temperature and humidity sensors. I want to do this wirelessly and I think the
best thing to do that is XBee.
I use this code for the transmitter Arduino:
char dataPacket[64];

int gx = 1;
int gy = 321;
int gz = 456;
int ax = 654;
int ay = 789;
int az = 987;
int mx = 147;
int my = 258;
int mz = 369;

void setup(){

 Serial.begin(9600);

}

void loop(){

   sprintf(dataPacket, "X%d" ,gx);
    //  sprintf(dataPacket, "A%dB%dC%dD%dE%dF%dG%dH%dI%d", gx, gy, gz, ax, ay, az, mx,     my, mz);
Serial.println(dataPacket);

    }

gx gy gz .... these are the sensor reading variables
and in the receiving Arduino I use this code
void setup(){
    // Start up our serial port, we configured our XBEE devices for 9600 bps.
    Serial.begin(9600);
}

void loop()
{

    if(Serial.available() > 0)
{
     while(Serial.available() > 0)
 {
        char dataPacket[64];

for (int i = 0; i < 64; i++)
{
  dataPacket[i] = Serial.read();
 Serial.print(dataPacket[0]);

}

String show = Serial.readStringUntil('C') ;
delay(500);

}
}
}

but i can't split the values from the stream and put them into their variables (gx gy ...)
Does anyone have idea how to split it?

Try a communication protocol with a , as a delimiter like:
messageId,data1,data2,data3,....,dataN\n

And use the Messenger library to parse it.
See my answer on comms protocols here:
Communication Protocol Best Practices and Patterns
An how to use the Messenger library here:
Send Processing color data into Arduino

You may be able to use sscanf() which works like a backward sprintf(), to assign the values from the input string into each variable.


text:
Arduino Timer Button
I am wandering how I would make it so the arduino uno will start a timer when button a is pressed and send "Start" or "Begin" or something like that to the console window. after the timer has started when button b is pressed it will mark the time from start of the timer and put it in the console window. After the timer has started when button c is pressed it will mark the time from start of the timer and put it in the console window. So on and so forth until button e, when button e is pressed i need the time to get logged in the console and they say "End" or "Stop" or something and then pause the sequence until I restart the board. This is for a school project and my only issue really is how to log the times On a timer loop persay.

What should happen if any of b-e are pressed while timer isn't running?

+jwpat7 Preferably Nothing. If anything just say something in the console to dis regard it.

Also, My buttons (I dont know if there is another way) are connected all to 5V and the other end (Through the Switch) goes to say for example Digital Pin 9. And then the next to DP 10. So on.

Ordinarily, posters are expected to say what they've tried so far, and to show the code they've written.  However, with a problem as difficult as this one, it seems reasonable to illustrate a complete program.
Note, this program assumes that one side of each button goes to Ground and the other side goes to a digital pin with its input pullup turned on.  (If you connect one side to +5V instead of to ground, you will need additional circuitry to sense button presses.)  The digital pins that are used are selected by changing the values swA, swB, and so forth, in the third line of the program.
//  jw - 8 Mar 2016 - Program for buttons demo
// Ref: http://arduino.stackexchange.com/questions/21590/arduino-timer-button
enum { swA=8, swB=9, swC=10, swD=11, swE=12}; // Switchbutton lines
enum { nSwitches=5 };
byte buttonPins[nSwitches]={swA, swB, swC, swD, swE};
byte buttonBusy[nSwitches]={  0,   0,   0,   0,   0};
unsigned long startTime;
//--------------------------------------------------------
void setup() {
  for (int i=0; i<nSwitches; ++i)
  // Note, this code assumes one side of button goes to Ground
  // and other side to a digital pin with its input pullup turned on
    pinMode(buttonPins[i], INPUT_PULLUP);
  Serial.begin(115200);
  Serial.println("Program begins");
}
//--------------------------------------------------------
void doButton(byte b) {
  char *blabels[] = {"A, Start", "B", "C", "D", "E, End"};
  if (digitalRead(buttonPins[b]) && !buttonBusy[b]) {
    // The b'th button has freshly turned on.
    unsigned long now = millis();
    if (b>0 && !buttonBusy[0]) // To ignore B-E if A isn't on
      return;
    buttonBusy[b] = 1;
    if (b==0) startTime = now;  // Button A resets timer
    Serial.print("Button ");
    Serial.print(blabels[b]);
    Serial.print(" at time ");
    Serial.println(now-startTime);
    if (b==nSwitches-1) {   // Last Button ends timing, restarts cycle
      for (byte k=0; k<nSwitches; ++k)
        buttonBusy[b] = 0;  // Clear all the busy-flags
    }
  }
}
//--------------------------------------------------------
void loop() {
  for (int b=0; b<nSwitches; ++b)
    doButton(b);
}

Edit: Note that triggering messages on button-release instead of button-press would be relatively easy if buttons didn't bounce.
Before explaining that, let's look at why the above code should work.  Assume the cycle (buttons A and later E getting pressed, and possibly some of B, C, D too) lasts at least a couple of seconds.  Assume we have ordinary button hardware, and that contacts can bounce for several milliseconds at each make or break.  When you press a button the Arduino sees a lot of pin-turning-on events, eventually settling at pin-is-on.  When you release a button the Arduino sees a lot of pin-turning-off events, eventually settling at pin-is-off.  And finally, assume each button press is long enough that at least one digitalRead() happens while contacts are closed.
Under those assumptions, the very first time in each cycle that we see a given button closed, we know that button has just been pressed.  Also, we can plausibly expect closure of button A to register before closures of other buttons, and can expect the closure of E to register after that of other buttons.  So we can ignore bounce.
On the other hand, with on-release triggering we need to distinguish whether a pin-turning-off event is due to contact bounce of a button just pressed, or is actually part of a button-release bounce sequence.
Here's a method worth considering if you want to implement trigger-on-release:
 • First, add a delay(1) call, in loop().  This will make the code timing less processor-dependent, so it can run on a 48- or 72-MHz system as well as on 16-MHz Unos.
• Each time you detect that button b is on, execute buttonBusy[b] = 40 to start (or restart) a 40-ms timeout.  That is, while a button is held down, we keep setting its timeout to 40.  (40 ms may be overly conservative.  20 ms should work ok with most switches, and 10 is ok with a lot of them.)
• When you detect that button b is off,
 • if buttonBusy[b] is zero, do nothing.
 • if buttonBusy[b] > 0, then decrement buttonBusy[b] and test if it now is equal to 1.  When it's equal to 1, regard b as released, so do its action.

+jwpat7 This suits me perfect! Thanks! But one question. How would I make it so on button release it does this (all buttons are pressed and trigger when released. ) (For my personal Knowlage. ) THANKS!!

See edit re that


text:
How to program pressure sensor and motor with motor shield
I was working on controlling a high power motor with a heavy duty motor controller, and I was able to make my motor spin, but I wasn't able to incorporate a program for my pressure sensor and make it determine the speed of the motor.  I'm pretty sure I connected the parts correctly on my circuit board, so I figure my code must have some mistake, or something missing.
The pressure sensor I'm using:
The motor controller I'm using: http://www.robotshop.com/en/arduino-compatible-mega-motor-shield-1a-5-28v.html#Useful
The code I have:
int motorValue=0;
int sensorValue=0;
int sensorPin=A0;
int EnablePin=8;
int PWMPin2=3;

void setup() {
  // put your setup code here, to run once:
pinMode(EnablePin, OUTPUT);
//pinMode(sensorPin, OUTPUT);
Serial.begin(9600);
pinMode(PWMPin2, OUTPUT);
pinMode(sensorPin, INPUT);
}

void loop() {
// put your main code here, to run repeatedly:
sensorValue = analogRead(sensorPin);

//float voltage = sensorValue * (5.0 / 1023.0);

//Serial.println(voltage);

delay(50);

motorValue=map(sensorValue,0,1023,0,255);
//motorValue=sensorValue / 4;
//analogWrite(motorPin,motorValue);
digitalWrite(EnablePin, HIGH);
analogWrite(PWMPin2, motorValue);
}

Edit: The sensor works by reading the voltage.  Here's an actual picture of how I wired it:  I used this wiring to print out the voltage with just the Arduino and it worked, and I'm using it with the same wiring but while having the motor shield on top, so that's why I'm guessing that I must not be programming the sensor right with the motor controller.  I couldn't get the voltage readings when I used this setup with the motor driver shield.

"I'm pretty sure I connected the parts correctly" - You may be pretty sure, but we aren't certain at all. Can we maybe see what you have wired up and how it is all connected?

Besides adding a schematic and a photo, you might explain how or why motor speed is related to "pressure" in your setup.  Ordinarily, speed is sensed using an encoder, or a tachometer, or a Hall sensor, or voltage readings, etc. rather than "pressure"

This won't make a difference but the ground and 5V from the arduino are not going to the correct spot on the breadboard. Change that to keep things standard, as if there were polarized parts there they would be dead. Also where does the red line go from the side of the flex pot?

I changed the polarity of the ground and the 5V, but it didn't seem to make a difference, as you stated.  I had the red wire going to negative in the picture, but now it's going to the positive.  The odd thing I noticed; I got tiny voltage readings when I pushed on the sensor, but much lower than they should have been, like 0.01-0.05, when it should've been more like 1 to 5 given how hard I was pushing.  So some voltage must be getting through, but somehow not enough.

How about uncommenting the logging code so you can see what it is reading with the motor shield installed and being commanded.  Also make sure that the motor shield doesn't wire something to A0, either as a control signal or as potential feedback (motor current sense, for example).

Depending on the jumper settings, the MegaMoto shield will drive current sense voltages onto one or two of the Arduino analog inputs.
Your picture shows the shunt installed to drive A0, which is of course going to conflict with your attempt to use the same pin for the force sensor.
If you are not using current feedback, it seems like you may be able to just remove that jumper, otherwise you will need to pick distinct pins for the current sense and your force sensor.  Consult the manual to be certain.
(The other placement of the other jumper in that block looks a bit suspicious too, almost seems it may be shorting the two current sense channels together, but not certain about that)


text:
Fast PWM with Arduino, the inputs outputs don't work
Hello to the community!
I am using ATTINY85 and I am programming it through the AVRISP using an Arduino UNO.
This is the code I am using :
#include <avr/io.h>
#include <avr/interrupt.h>

void setup() {
    PORTB = 0;        //Reset values on port B

    // After setting up the timer counter,
    // set the direction of the ports to output
    DDRB |= (1<<PB1) | (1<<PB0) | (1<<PB3); // PB0, PB1 and PB3

    // PLLCSR - PLL control and status register:
    // PLL is a clock multiplier
    //      - multiplies system 8 MHz by 8 to 64 MHz
    // PLL is enabled when:PLLE bit is enabled,
    // CKSEL fuse is programmed to 0001.  This clock is
    //   switched off in sleep modes!
    PLLCSR |= (1<<PLLE);    // PLL enable

    // Wait until the PLOCK bit is enabled
    // before allowing the PCK to be enabled
    //WaitForPLOCK();
    //unsigned int i = 0;

    while ((PLLCSR & (1<<PLOCK)) == 0x00)
    {
        // Do nothing until plock bit is set
    }

    // Enable asynchronous mode, sets PWM clock source
    PLLCSR |= (1<<PCKE);

    TCCR1 = (1<<CTC1)    | // Enable PWM
            (1<<PWM1A)   | // Set source to pck
            (0<<(CS13))  |
            (0<<(CS12))  |
            (1<<(CS11))  |
            (1<<(CS10))  | // Clear the pin when match with ocr1x
            (1<<COM1A1);
    GTCCR = (1<<PWM1B) | (1<<COM1B1);

    // Set PWM TOP value - counter will count and reset
    //  after reaching this value
    //           OCR1C
    // 100 kHz   159
    // 80 kHz    199
    OCR1C = 199;

    // Enable Timer1 OVF interrupt
    TIMSK = (1<<OCIE1A) | (1<<TOIE1);

    sei();

    OCR1A = 190;  //chaning th FR
}

void loop() {
    PORTB |= (1 << PB3);
    delay(500);
    PORTB &= ~(1 << PB3);
    delay(500);
}

the problem is that when I use the PWM my rest of the outputs do not work . Any idea why is this happening?
I am using the ATTINY CORE library from Spence Konde.

This line:
TIMSK = (1<<OCIE1A) | (1<<TOIE1);

enables a couple of interrupts generated by Timer 1. Whenever you
enable an interrupt source, you should make sure that the matching ISR
has been defined. Otherwise, the interrupt request is routed to
__bad_interrupt(), which by default jumps to the reset vector, thus
resetting your program.

Amazing!! Thank you! That worked out!


text:
What is the frequency of PWM output on Arduino
What frequency do Arduinos use for normal PWM when you use analogWrite()?
And is it different for different Arduino model? I'm interested specifically in the Mega 2560, but also want to know if it's consistent between models.
I've seen a passing references to the Arduino using 500 Hz, which seems really slow.

That also depends on the pin you are using.

The PWM signal is generated by timers on the AVR chips. Each timer can generate a PWM signal on two or three different pins. Each pin can have it's own duty cycle, but they share the PWM frequency. You can change the frequency of the PWM by changing the clock source for the timers. By default they use the CPU clock divided by 64, ie. they have their prescaler set to 64 by Arduino initialization code.
  To confuse things more there are two different PWM modes: fast PWM and phase correct PWM. In fast PWM the timer counts to 255, then overflows and starts over from 0 (256 different states). In phase correct PWM the timer counts to 255, then changes direction and counts downwards to zero, changes direction and so on (510 different states).
The Arduino Mega has 5 timers, timer0 - timer4. Because timer0 is also used for the millis and micros functions it uses fast PWM, whereas the other timers are configured for phase correct PWM. This results in different frequencies on different pins:

Pin 4 and 13, controlled by timer0:
16 Mhz / 64 / 256 = 976.56 Hz
Other PWM pins, controlled by timer1-4:
16 Mhz / 64 / 510 = 490.20 Hz

The calculation is: Clock / Prescaler / PWM mode number of states
The situation is the same for all other Arduino boards I know of, except they have less timers that connect to different pins.
You can change the PWM frequency by changing the timer prescaler. See this page: http://playground.arduino.cc/Main/TimerPWMCheatsheet
It is also possible to make the timers count to a different value than 255. On the 8 bit timers you will loose an output pin, but on the 16 bit timers you can use the Input Capture Register to define a TOP value. The input capture functionality is a feature rarely used in the Arduino community so you likely won't miss it.
The Arduino libraries only allow you to use 8 bit resolution, even on the 16 bit timers. If you want the higher resolution, you will have to write your own analogWrite, or use a library made for the purpose.
On the Arduino Mega timer0 and timer2 are 8 bit, while the rest are 16 bit.
By changing the mode of the 16 bit timers to make use of the full resolution, in combination with changing the prescaler and the TOP value, you can achieve a very wide range of PWM frequencies.
The maximum frequency you can achieve is clock / 4, by setting the prescaler to 1 and TOP to 3 in fast PWM mode - a lower value isn't allowed. This will give you a 4 MHz PWM with 2 bit resolution. It can be on 0%, 25%, 50%, or 75% of the time. A higher TOP value will give you a higher resolution at a lower frequency.
For a longer explanation read this article or refer to the datasheet.
Changing the prescaler, PWM mode, or TOP value for timer0 will mess with millis() and micros().

I gather, then, that the fastest frequency you could get for PWM is 16Mhz/256 (prescaler = 1), or 62.5Khz?

And further that the PWM frequency has to be an even factor of 62.5KHz? Somebody on another thread wanted to control the fan speed of a 4-pin PC fan. Apparently it wants a PWM control signal of 25KHz. 62.5/25 is 2.5, which is not an integer value.

I updated the answer to elaborate more on the possibilities of achieving specific frequencies,

On the low frequency end, you could prescale a 16 bit timer in phase-correct mode by a 1024 prescaler  to get 16e6/1024/2^16/2 = 0.119Hz, or 7.1 cycles/minute.   For lower than that, one would need to toggle the bits based on something like millis().   Or maybe trigger the counter on the external input pin T?.


text:
How to stop uno from running program when powered on?
Does anyone know how to prevent the Uno from running the last program when it's powered on?
Many times I have changed hardware and wiring without clearing the program first.  Then when I power it on to upload the new program it will run the old program until it's uploaded.  This has many potential unwanted effects when the old program is running with the new hardware installed.

The simplest thing is to upload the new program before connecting the hardware.
If this isn't practical, connect a jumper wire from the Reset pin to ground (Gnd) before powering it on. This will hold in a reset state, and the program won't run.
Then, compile and upload your program. As it starts to upload remove the reset wire. That should upload it without running any existing program.

Thanks,  Sometimes for big projects with lots of connections this feature would be useful.  Should the reset button have the same effect?  Is there documentation on the feature?  Thanks.

I'm not sure about documentation - well there is now, in the answer here. :) The Reset button would have the same effect but it can be tricky holding it down with one hand and uploading the new code with the other.


text:
DC motor makes noise but does not rotate
i am following Jeremy blum's tutorial on youtube. link i have done the exact same circuit design as he has.

but the dc motor just makes a continuous beep sound when i run this code.
int motorPin = 9;

void setup()
{
    pinMode(motorPin, OUTPUT);
}

void loop()

{
    for(int i = 0; i <= 255; i++)
    {
        analogWrite(motorPin, i);
        delay(10);
    }

    delay(500);

    for(int i = 255; i >= 0; i--)
    {
        analogWrite(motorPin, i);
        delay(10);
    }

    delay(500);
}

I am clueless as to why this is happening. would be glad if someone could help me out here.

What are the specs of your motor (current rating)? What is the transistor model you have used?

Could be an AC motor. Try connecting it directly to a 9v battery or some other power source, and see if it turns

Or just change pin 9 to HIGH to see if your circuit is working right an inertia is stopping the motor from turning.

For the benefit of anyone reading Jeremy Blum's Exploring Arduino book who is having the same issue- he has labelled the transistor wrong in the book so the collector and emitter are back to front. Turn the transistor around to face the other way and your issue will be resolved.

analogWrite uses PWM. Is the motor you are using designed for pulsed operation? Try using
digitalWrite(motorPin, HIGH);

The question should be not so much if the motor is designed for pulsed operation, but if the duty cycle, supply, and driver circuit are delivering sufficient power.  Commanding 100% duty cycle in this manner is indeed one of the key tests which should be run (except in the atypical case where the driver is capable of delivering an unsafe amount of power)

I'm wondering if a 10 ms delay between steps is long enough for the motor to respond, especially with a cap across its terminals.  Besides that the whole thing is over in 5 seconds.
It seems to me that AnalogWrite generates a PWM signal of about 500hz or about 2ms wave period.  So in 10 ms you get 5 pulses of the same amplitude and smoothed by the cap.  At low values of "i", say i=10, then the pulse is only 10/255*2ms wide or about 78uS. At low values of i, a 180deg rotation has to occur in the time you apply the pulse for the motor to rotate, well not exactly but close enough.
Most small DC motors are 2 pole, so you're expecting at least one 180degree rotation in 5x78uS or about in 400uS.  That would be a full rotation in about 800uS, say 1mS, or 1000 rotations in 1 second, or 60000rpm, from a standing start if the duty cycle was held constant.  You have very little power at low "i" so I'd be surprised if there is enough to overcome friction and inertia.  On higher values I guess it's still not enough to overcome the inertia.
The motor well may run at the higher values of "i" but then the program immediately counts down again.
So I suggest you start the counter at say 125 or even higher. Also make the delay between counting up and counting back down much longer so you can actually see the effect before it counts down again. I would also want to make the delay between counts higher so there is more time for current to flow in the motor's (inductive) windings.  Remember an inductor resists a change in current. Now that I think about it, this is probably more important than the inertia and friction.
So here is a challenge... Change the delay between counts first, and report your results here.  Then reset that and change a different parameter, and so on. Eventually make a number of changes together...I'm curious to see the outcome.
By the way, I suspect the sound is from the motor laminations changing shape at high frequency.
Cheers
P

I had the same issue, turns out that i had configured the BJT wrong. I had confused the drain for the collector.


text:
How to check if all pins are connected on my board to make sure Arduino sends the correct pattern number on my tool
What to add on this code to check my pins state during run? And how can i trigger error using Visual basic when 1 of my pin is disconnected?
String input = "";

void setup(){

Serial.begin(9600); // Sets up communication with the serial port

pinMode(6,OUTPUT);
pinMode(7,OUTPUT);
pinMode(8,OUTPUT);
pinMode(9,OUTPUT);
pinMode(10,OUTPUT);
pinMode(11,OUTPUT); // for start of program operation
pinMode(12,OUTPUT); // for stop of program operation

digitalWrite(6,LOW);
digitalWrite(7,LOW);
digitalWrite(8,LOW);
digitalWrite(9,LOW);
digitalWrite(10,LOW);

digitalWrite(11,LOW);
digitalWrite(12,LOW);

}

void loop(){

int recipe;
//Serial.print("Enter recipe number: ");

while(Serial.available()==0){    // Waits for data from serial port
}

while(Serial.available() > 0){
int data = Serial.read();
  // convert the incoming byte to a char
  // and add it to the string
input += (char)data;

recipe = input.toInt()+'0';    //recipe=0 if not a digit
if(recipe == '0')
  recipe = data;

if(data == '\n'){
  //Serial.print("Recipe: ");
  //Serial.println(recipe);
  //Serial.print("String: ");
  //Serial.println(input);
  input = "";
}
}

if(recipe == 's'){
digitalWrite(11,HIGH);
delay(1000);
digitalWrite(11,LOW);

digitalWrite(6,LOW);
digitalWrite(7,LOW);
digitalWrite(8,LOW);
digitalWrite(9,LOW);
digitalWrite(10,LOW);
}

else if(recipe == 't'){
digitalWrite(12,HIGH);
delay(1000);
digitalWrite(12,LOW);

digitalWrite(6,LOW);
digitalWrite(7,LOW);
digitalWrite(8,LOW);
digitalWrite(9,LOW);
digitalWrite(10,LOW);
}

else if(recipe>'0' && recipe<'32'){

recipe = recipe-'0';
char binary[7] = {0};   // This is where the binary representation will be stored
recipe += 32; // Adding 32 so that there will always be 6 digits in the string
itoa(recipe,binary,2);  // Convert recipe to a string of base 2 and save it in array 'binary'
char* signals = binary + 1; // Get rid of the most significant digit to get the 5 bits

//Serial.print(signals);    // Print out the signals in binary

int i;
for(i=0; i<5; i++){
  if(signals[i] == '0')
    signals[i] = '1';
  else
    signals[i] = '0';
  digitalWrite(i+6, signals[i]-'0');    // write to pin; converts the bit of the string to HIGH or LOW
  //Serial.print(signals[i]);
}

}
else
loop();

}

Welcome to Stackexchange. Please ask a question. And please post your code in a readable format (see editor help).

It's probably not possible to know how an interrupted signal can be recognised in code as long as we don't know how you connect them. Without external logic only input pins could do this in code and even then Arduino has a lot of them.

I have attached the connections of my pins to the tool controller. The purpose of this setup is Arduino will send the data from my traveller to my tool then automatically start my tool once data was received. Since the data from my traveller is critical and Arduino must send the correct value to the tool prior start. The only thing i need to know is that how can i detect if my pins are connected properly

If a pin gets disconnected, Arduino won't recognise it as is. This would require some form of feedback from the tool controler, e.g. by bringing another set of wires from the connection terminals back to some of Arduino's input pins. Also, your code still contains errors (e.g. you call loop() from within loop()). And then there's Visual Basic all of a sudden. :) May I suggest you compile this into different questions?

As mentioned in a comment, your code has some fundamental flaws. Do not call loop() from within loop()! Aside from the code errors, your question has a legitimate element.
Testing the tri-state behaviour of an input pin will let you know if it is genuinely high, genuinely low, or floating (disconnected). The technique was given in this answer to similar problem I was encountering.
In short:
Connect a large (1MOhm) resistor to each input between the pin and ground, then for each pin:

Turn off internal pullup;
Read value of input pin;
Turn on internal pullup;
Read value again.

If the value changes from the first to the second digitalRead(), the input was not connected to anything. If the value remains the same then it is a genuine value from a connected device.

+1, Great answer to the original issue of detecting an open pin. It's also in line with my suspicion that external hardware is required: feedback to input pins... ;)

That being said, what about shorts to ground or supply, what if the impedance in the machine is too low for this approach... I have a suspicion that this arduino shall double as a failsafe device in order to protect the machine and people – and that involves much more.

If it is for a truly safety-critical application then there should be many more steps taken, the first being a second processor (complete Arduino board) for a Master/Slave setup. Then there's 'toggle-checking' of all the inputs as the next step. However, if the OP posted this question in the first place then they should not be responsible for designing something so technical.


text:
ATMEL SAMD11 SPI (Slave) With Arduino (Master)
I am trying to get my Atmel SAMD11 XPLAINED PRO and arduino to talk to each other using SPI. I have set up the arduino as the master, with the SAMD11 as the slave. On the ATMEL, I have the following code:
http://asf.atmel.com/docs/latest/samd21/html/asfdoc_sam0_sercom_spi_slave_callback_use.html
Essentially, it waits until the master sends data, compares the data with what it expects, and updates an LED accordingly. On the arduino side, I have the following:
#include <SPI.h>

#define BUF_LENGTH 20
int slave_select = 10;

void setup (void)
{
  // Initialize serial for DEBUG.
  Serial.begin(9600);
  pinMode (slave_select, OUTPUT);
  digitalWrite(slave_select, HIGH);  // ensure SS stays high for now
  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.beginTransaction (SPISettings (4000000, MSBFIRST, SPI_MODE0));  // 4 MHz clock, MSB first, mode 0
  // Master initialized.
  Serial.println("Master Initialized");
}  // end of setup

void loop (void)
{
  static uint8_t buffer_expect[BUF_LENGTH] = {
    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
     0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13
  };
  // enable Slave Select
  digitalWrite(slave_select, LOW);    // SS is pin 10

  //write the 20 bytes
  for (int I=0;I<20;I++)
  {
    SPI.transfer(buffer_expect[I]); //write data byte
    delay(20);
  }

  // disable Slave Select
  digitalWrite(slave_select, HIGH);

  delay (1000);  // 1 seconds delay
}  // end of loop

When I run the code, the LED on the SAMD11 isn't updated, which means that it is waiting for data to be sent, and hasn't received any, despite what the arduino code writes. On the hardware side, I have GND connected on both boards, VCC on the SAM to 5V on the arduino, and SPI_SS_A, MOSI, MISO and SCK connected to pins 10,11,12 and 13 on the arduino respectively.

I don't see a "pinMode" statement anywhere in your code. Where do you set SS as an output?

You haven't set your SS pin as an output anywhere in your code.
The arduino page you linked to has a note near the bottom which reads:

Note about Slave Select (SS) pin on AVR based boards
All AVR based boards have an SS pin that is useful when they act as a
  slave controlled by an external master. Since this library supports
  only master mode, this pin should be set always as OUTPUT otherwise
  the SPI interface could be put automatically into slave mode by
  hardware, rendering the library inoperative. It is, however, possible
  to use any pin as the Slave Select (SS) for the devices. For example,
  the Arduino Ethernet shield uses pin 4 to control the SPI connection
  to the on-board SD card, and pin 10 to control the connection to the
  Ethernet controller.

The Example code given for the teensy board on the other page you linked has:
pinMode (slaveSelectPin, OUTPUT);

in its setup() function.
So that's what you're missing.
Setting the pin high or low is not going to achieve anything if its not an output.
Remember that SPI can access many diffrent devices using the same MOSI/MISO/SCK pins, but each slave device has its own Slave-Select pin which needs to be individually driven by the master.
Your master can therefore have many different SS pins, all set as outputs - and there is no single standard pin for this.

It doesn't seem to be this, I have updated the code and I have the same issue, where the SAMD11 doesn't have a lit LED, meaning it is waiting to receive something.


text:
Transfer a struct's data to an external struct via serial?
Using two boards of similar architecture I would like to send the contents of a struct from the sending board to the receiving board. I am using UART to transfer.
My plan was to populate an array with the starting structs data. Transfer that, than un-package the array onto the receiving boards struct.
I'm not sure this is a possible option. Unpacking the array seems sort of rigid, as I would be assigning each struct variable to the array index. It might work but I'm not really convinced I should do it this way.
Here's what my sending sketch looks like.
Send:
typedef struct NWK_DataReq_t
{
 uint8_t      state;
 uint8_t      options;
} NWK_DataReq_t;

//Instance struct
NWK_DataReq_t dataRequest;

void setup()
{
  //Give it some values
  dataRequest.state = 2;
  dataRequest.options = 4;

  Serial.begin(9600);
}

void loop()
{
  //set variable array to struct length
  uint8_t payload[sizeof(dataRequest)];

  //copy struct to variable array
  memcpy(payload,&dataRequest,sizeof(dataRequest));

  //send each item of struct, now contained in payload array
  for(int i=0;i < sizeof(payload);i++)
  {
    //Serial.print(i);
    //Serial.print(":");
    Serial.println(payload[i]);
  }

  Serial.println("");
  delay(1000);
}

Receive:
typedef struct NWK_DataReq_t
{
 uint8_t      state;
 uint8_t      options;
} NWK_DataReq_t;

//Instance struct
NWK_DataReq_t dataRequest;
uint8_t incomingPayload[sizeof(dataRequest)];

void setup()
{
  Serial.begin(9600);
  Serial.print("Recieve started");
}

void loop()
{

  if (Serial.available())
  {
    //add incoming data to array
    for(int i=0;i<sizeof(dataRequest);i++)
    {
      uint8_t incomingByte = Serial.read();
      incomingPayload[i] = incomingByte;
    }
  }

  //set array values to structs
  for (int i= 0;i < sizeof(dataRequest);i++)
  {
    structIndexPosition = incomingPayload[i];
  }
}

structIndexPosition is not attached as I wasn't sure how I might index the struct, or if this is an okay approach.

You might want to look at my ICSC library. It handles this kind of transfer very cleanly and reliably. Feel free to use it, abuse it, rip it to bits, steal bits from it, learn from it, get ideas from it, whatever: https://github.com/MajenkoLibraries/ICSC

The simplest possible way of sending the struct's data is:
Serial.write((const uint8_t *)&myData, sizeof(myData));

Get the address of myData, cast it to an unsigned int pointer, and starting at that address write the number of bytes specified by sizeof(myData). That will transfer the raw data of the struct through the serial with no messing with copying of data into other arrays, assigning pointers, etc.
However: it won't work.
Sending raw binary data over serial like that, where serial has no concept of anything other than bytes, it is just not possible to know where in the stream of data you are. Which of the myriad of bytes coming in is which within a struct?  Who can tell?
So you need to write a protocol. A method whereby one end tells the other end "This is the start of the data.  This is the data.  This is the end of the data."  But also you need to be able to say "This bit, that looks the same as the 'start of the data' message is actually a bit of the data, not the start of the data".  You see, it's quite an involved task really.

I think you are over-complicating it to send two bytes. Just send them as straight ASCII with a newline after, and decode it on the receiving end.
eg.
42,87

However if the question was just an example of something much more complex, then you may need to do more work. You need to have the receiving end know when a packet of data starts, and ends, and preferably have some validation that it wasn't corrupted.  If you want to pursue that idea, see my thread about sending data via RS485 which has a library that does that sort of thing.

Thanks for the link, Nick. It will be more complex than this. I'll be looking into validation shortly, just wanted to get some basics straight.

If you couldn't run this code like me then all you have to do is cut the:"
struct package
{
};
typedef struct package Package;
Package data; "
And paste it into the "void loop" and it should work fine.
P/s: Thank you very much for this helpful video, but hope you will update this in the future ( i guess the update had changed something in the Arduino codes)

For what it's worth I'm looking at the question and looking at your answer and it almost looks like you're answering a completely different question from the one being asked.  But, I can't tell for certain.

Why go over the bridge for water?
It is possible to access the data in the struct as a character pointer. No need to transfer to a buffer etc.
void loop()
{
  ...
  ...
  const char* dp = (const char*) &dataRequest;
  for (int i = 0; i < sizeof(dataRequest); i++) Serial.print(*dp++);
  Serial.println();
  delay(1000);
  ...
  ...
 }

It might be hard to extrapolate how to receive this?
void loop()
{
  if (Serial.available() > sizeof(dataRequest)) {
     char* dp = (char*) &dataRequest;
     for (int i = 0; i < sizeof(dataRequest); i++) *dp++ = Serial.read();
     Serial.read();
     ...
     ...
  }
}

The Serial.println() and extra Serial.read() could be replaced by a "frame marker" and/or a check-sum.
Cheers!

Okay, but how would I populate the new struct with dp?

It appears to be working, some of the time. I have a Serial.print(dataRequest.options) line to confirm. It sometimes reaches 4, but also reaches a couple other numbers in a looping pattern.


text:
Why am I only receiving the first address byte? (I2C Protocol)
Expecting the slave to ACKnowledge and return data, but it does not. This is my protocol. This is my Datasheet.
Also FYI I'm on an Arduino Fio but I am not inheriting the Arduino library.
#include <avr/io.h>
#include <util/delay.h>
#include <stdlib.h>
#include <uart.h>
#include <i2c_master.h>

#define LED PB5

#define I2C_READ 0x5A

char buffer[1];

//char data[9];
uint16_t val = 0;
uint8_t status = 0;

void getVal()
{
  if(i2c_start(I2C_READ))
    {
        uart_puts("Start ");

        val = ((uint8_t)i2c_read_ack())<<8;
        val |= i2c_read_ack();

    status = ((uint8_t)i2c_read_nack());

      i2c_stop();

    } else
  {
        uart_puts("Error");

        i2c_stop();
    }
}

int main(void)
{
  init_uart(57600);
  i2c_init();

  DDRB = _BV(5);

    for(;;)
    {

      getVal();

            itoa(status, buffer, 10); //convert decimal to string base 10
            uart_puts(buffer);

      PORTB = 0xFF;
      _delay_ms(500);
      PORTB = 0x00;
      _delay_ms(500);
    }
    return 0;   /* never reached */
}

(Acknowledging this is an old question.) The TI article "Troubleshooting I2C Bus Protocol", suggests several common reasons for no ACK:
1. Timing
2. Missing / Unexpected SCL pulses
3. Incomplete 8 bit block
4. Missing Bytes
5. False slave address
6. Unsuccessful address change


text:
Why perform bitwise operations here? (SPI FRAM read method)
See: https://github.com/adafruit/Adafruit_FRAM_SPI/blob/master/Adafruit_FRAM_SPI.cpp
The following method reads and converts the input to 8 bit. I have several questions concerning its function.
Using addr = 0xFFFF as an example, the method converts the variable to 0xFF. I understand that bits are removed from the end, but surely 65535 != 255. Perhaps relatively, to their max size, but how is this a useful conversion? I might be missing something about bitwise here..
uint8_t Adafruit_FRAM_SPI::read8 (uint16_t addr)
{
 digitalWrite(_cs, LOW);
 SPItransfer(OPCODE_READ); //read memory from fram array (2-byte)
 SPItransfer((uint8_t)(addr >> 8));
 SPItransfer((uint8_t)(addr & 0xFF));
 uint8_t x = SPItransfer(0);
 digitalWrite(_cs, HIGH);
 return x;
}

Correct me if I'm wrong, the casting is to keep sign extension from occurring.
The masking I understand in theory, but do not at all understand its application here.
Finally, it always returns the same value x = 0, why?
I also see there's a write method but no read method. Only read8. Reasoning?

Think about what happens to the numbers and then plug those into 4 SPI transfers and think about what actually then happens on the SPI bus.

The code above first send the highest 8 bits of the address (addr>>8), and then the lowest 8 bits. Not sure why they do both masking  and casting. After that it sends 8 zero bits. During the sending of those bits the FRAM send the value in the address to the arduinos MISO pin. The 8-bit value is stored in the `x variable. Note that SPI is bi-directional, and you can send and receive data at the same time.

Let's assume addr is 0xbeef. Then, if we break down each operation:
expression             │ value
───────────────────────┼───────
addr                   │ 0xbeef
addr >> 8              │ 0x00be
(uint8_t)(addr >> 8)   │   0xbe
addr & 0xFF            │ 0x00ef
(uint8_t)(addr & 0xFF) │   0xef

So this is essentially breaking down the address into two 8-bit chunks,
and transmitting those chunks individually. It's done like this because
SPI only transmits bytes.

the casting is to keep sign extension from occurring.

Non, sign extension cannot occur, since addr is an unsigned number.
The casting really serves no useful purpose, other than documenting the
code. It would be done implicitly simply because SPItransfer() takes
an uint8_t argument. The casting could be useful if SPItransfer()
was overloaded with a 16-bit version.

Finally, it always returns the same value x = 0, why?

No, it returns whatever the call to SPItransfer(0); returns, i.e. the
data sent by the FRAM module.


text:
Is the DigitalWriteFast library still needed?
Yesterday I played with a SRAM 621024 SRAM 1 Mbit IC and since I use a lot of pins, digitalReads and digitalWrites are needed including shift registers (see Example
Since it took a long time for reading/writing one byte, I checked for faster ways and found some posts, one of them was using digitalWriteFast:
Library
However, it did not make any difference... is it possible that the (fast) digitalWrite is already implemented in the default Arduino IDE/library?
Update: I found out I made a stupid mistake and the library was not used.
Now I get different values:

Writing 397.880 us per byte
Reading 386.524 us per byte

Without the fast library:

Writing 502.152 us per byte
Reading 483.752 us per byte

Note, there is also a digitalReadFast, but this does not affect the speed.
I did some more testing and found out that a digitalReadFast/digitalWriteFast cost just about 8-12 us, a pinModeFast is 0 us (negligable), however a shiftOut for setting the address cost 120-124 us ... since 3 shifts are needed to set an address, this results in 360-372 us. Subtracting this from the measured times above, writing takes around 25-38 us and reading 15-27us. I possibly can maybe optimize the bit operations a little bit.
However, the end result for using this RAM chip with enough speed is to either change the shift register to a faster one or remove the shift registers at all. This would mean about 30 pins needed for the SRAM only. The conclusion is: better use a 3K256, 23LC1024 or similar variant.
(Note: I tried a ShiftOutFast file), which reduces a shiftout to 36 us but 3 times 36 is still over 100 us, too much to compare to a 3K256/23LC1024 solution.

If it made no difference then the chances are the bottleneck isn't the digital pin manipulation.

I didn't get a microsecond difference.

The time taken to use digitalWrite() pales into insignificance compared to the time taken to use shift registers.

Yes it seems so ... I already thought that shift registers would not be beneficially for a SRAM solution ... maybe when I have the Arduino Mega I will check direct pins (like 32 pins maximum). Than I don't need shift registers. If I ever will solder that solution, I doubt :-)

The current digitalWrite() still does quite a lot of stuff.

That's why I was surprised I did not see any difference.

Last time digitalWrite() changed was six years ago

I should point out that micros() has a 4 µs resolution, so a difference of less than 4 µs would not be measurable (if that is how you are measuring it).

@NickGammon Thanks for the info (although it does not make the conclusion much different)

a pinModeFast is 0 us (negligable) - it may in fact be 3 µs is my point. Unless you did a loop of 1000 of them, written in such a way that the compiler didn't optimize the loop away.

No not in this case, so negligible means 3 us (or less). Negligible is relative :-)

I just tried to time digitalWrite() against direct port access with
the following code:
void setup()
{
    uint16_t overhead, start, end;

    Serial.begin(9600);
    TCCR1A = 0;
    TCCR1B = 1;

    // Time digitalWrite().
    overhead = 7;
    cli();
    start = TCNT1;
    digitalWrite(2, HIGH);
    end = TCNT1;
    sei();
    Serial.print("digitalWrite(): ");
    Serial.print(end - start - overhead);
    Serial.println(" cycles");

    // Time direct port access.
    overhead = 4;
    cli();
    start = TCNT1;
    PORTD &= ~_BV(PD2);
    end = TCNT1;
    sei();
    Serial.print("direct port access: ");
    Serial.print(end - start - overhead);
    Serial.println(" cycles");
}

void loop(){}

The result was:
digitalWrite(): 78 cycles
direct port access: 2 cycles

I used an old Arduino core (1.0.5), but that function has not changed
since. You can try with your current core and see.
PS: In this program, the correct value for overhead can only be
determined by examining the generated assembly. It's a count of the
cycles you are measuring but do not directly belong to the operation you
really want to measure.

WOW! That's a difference! Very interesting to know. Where does all that extra MPU cycle usage come from?

@EnricBlanco: Here is the link to the source code again. Look at the disassembly: saving registers to the stack and restoring them back (20 cycles) table lookups, tests... and 8 cycles of call overhead.

is there any related trick like this for the ESP8266?

@dandavis: I have no experience on that chip.

authors: Александр Манылов


text:
How do I proceed with a fall detection sensor?
I am working on a human fall detection system using accelerometer and gyroscope which raises alarm in case of a fall. In all the papers I have read people have used net acceleration magnitude and compared it with a threshold and coupled it with change in orientation to detect fall. My question is would it be better to use acceleration in z-axis(normal to earth's surface) and compare it to threshold as compared to net acceleration as it might reduce false positives as net acceleration can exceed threshold in case of running but that won't happen if i take only acceleration in z-axis. Is my approach right?
How can I implement sensor fusion using a gyroscope and a magnetometer to find the orientation?

When's the last time you had something fall right along its Z axis?

What i meant was that using gyroscope values i will try to get the acceleration in original axis.And i wish to use that z-axis values.Rotating the axis.

Find the derivative of acceleration over time, also known as jerk. Falling will have a specific jerk pattern, whereas normal shaking and banging will have a completely differrent pattern.


text:
How to modify Arduino boards.txt to support new MCUs
In this post, it was mentioned that to get the Arduino IDE to support an ATmega328 (only the ATmega328P is supported):

I should mention the Arduino way of doing this, is to create a new
  boards.txt file with this chip and add (not change) the avrdude.conf
  file. This will allow programing either from selecting the correct
  board. but that is another subject.

After a great deal of research in the past, and attempted modifications to boards.txt and avrdude.conf, I arrived at the conclusion that the Toolchain doesn't support the ATmega328 therefore the changes will have no effect.
Can anyone confirm that they have successfully found a way to make these changes, so we can avoid the need for a work-around?

what is the error? the same as in that other post you link to?

See these links: http://computerpr0n.com/2012/03/burning-arduino-bootrom-on-an-atmega328-pu/ | http://forum.arduino.cc/index.php?topic=58670.0 | http://www.instructables.com/id/Bootload-an-ATmega328/step6/

Please, Note that the Arduino IDE is behind on many of the tools. In this case avrdude and its conf file, along with avr-gcc
First:
.\arduino-1.5.6-r2\hardware\tools\avr\etc\avrdude.conf

needs to support the m328 in addition to m328p. This can be done by either updating
.\arduino-1.5.6-r2\hardware\tools\avr\bin\avrdude.exe

to something like avrdude-6.1-svn-20131205-mingw32. along with replacing the conf file with the new one
.\arduino-1.5.6-r2\hardware\tools\avr\etc\avrdude.conf

file that has both m328 along with the m328p. Note 6.1 supports a parent method, making it easy to duplicate chips with different signatures. Or use existing 5.11 and add to its
.\arduino-1.5.6-r2\hardware\tools\avr\etc\avrdude.conf

file by duplicating the entire m328p section and renaming the new entry to "m328" along with the correct signature.
Second:
avr-gcc need to be updated to support compiling both the m328p and m328. Yes, it just a semantic thing. But the next part will send either ATmega328p or ATmega328 to both gcc and dude. which both need to support it. One can simply copy over
.\arduino-1.5.6-r2\hardware\tools\avr\

with the new tool chain. I used avr-gcc-4.8_2013-03-06_mingw32
Third:
replace the following line in boards.txt
uno.build.mcu=atmega328p

with
## Arduino ATmega328P
## ---------------------------------------------
uno.menu.cpu.atmega328p=ATmega328P
uno.menu.cpu.atmega328p.build.mcu=atmega328p

## Arduino ATmega328
## ---------------------------------------------
uno.menu.cpu.atmega328=ATmega328
uno.menu.cpu.atmega328.build.mcu=atmega328

This will add an option to the IDE when UNO is selected for either chip. And subsequently send the correct MCU to both the compiler and avrdude.

Proof:
Below are the verbose output of the IDE with the above changes. Note the -mmcu and -p for both options. As a real unit is was not connected it yielded the "not in sync" error. Where this shows it all works.
C:\projects\Arduino\arduino-1.5.6-r2\hardware\tools\avr\bin\avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -MMD -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=156 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -IC:\projects\Arduino\arduino-1.5.6-r2\hardware\arduino\avr\cores\arduino -IC:\projects\Arduino\arduino-1.5.6-r2\hardware\arduino\avr\variants\standard C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp\sketch_jul31a.cpp -o C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp\sketch_jul31a.cpp.o
...
C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp/sketch_jul31a.cpp.hex

Sketch uses 444 bytes (1%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
C:\projects\Arduino\arduino-1.5.6-r2/hardware/tools/avr/bin/avrdude -CC:\projects\Arduino\arduino-1.5.6-r2/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp/sketch_jul31a.cpp.hex:i

avrdude: Version 5.11, compiled on Sep  2 2011 at 19:38:36
...
avrdude: stk500_getsync(): not in sync: resp=0x00

avrdude done.  Thank you.

C:\projects\Arduino\arduino-1.5.6-r2\hardware\tools\avr\bin\avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -MMD -mmcu=atmega328 -DF_CPU=16000000L -DARDUINO=156 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -IC:\projects\Arduino\arduino-1.5.6-r2\hardware\arduino\avr\cores\arduino -IC:\projects\Arduino\arduino-1.5.6-r2\hardware\arduino\avr\variants\standard C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp\sketch_jul31a.cpp -o C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp\sketch_jul31a.cpp.o
...
C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp/sketch_jul31a.cpp.hex

Sketch uses 444 bytes (1%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
C:\projects\Arduino\arduino-1.5.6-r2/hardware/tools/avr/bin/avrdude -CC:\projects\Arduino\arduino-1.5.6-r2/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -patmega328 -carduino -PCOM3 -b115200 -D -Uflash:w:C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp/sketch_jul31a.cpp.hex:i

avrdude: Version 5.11, compiled on Sep  2 2011 at 19:38:36
...
avrdude: stk500_getsync(): not in sync: resp=0x00
avrdude done.  Thank you.

One draw back, may be that the new compiler will have some issues on poorly written code and libraries. IDE 1.0 and early complained with latest versions of gcc. Mostly bad coding that is easily corrected. Where I do believe for the addition of the ARMs these have been corrected. At least in the IDE's core libraries.

I'm curious if you can use uno.menu.cpu.atmega328=ATmega328
uno.menu.cpu.atmega328.build.mcu=atmega328p to get it to build for a 328p with the old compiler, but flash as a 328 (ie, looking for that signature).

I looked at that first. The \arduino-1.5.6-r2\hardware\arduino\avr\platform.txt uses {build.mcu} in both the compile and avrdude. Alternatively (and not pretty) would be to define a ...build.mcu_upload in the boards.txt and replace the "-p{build.mcu}" with -p{build.mcu_upload}. However, this would require that all entries in the boards.txt have the added build.mcu_upload" added. (not very clean). This does have the advantage of supporting both chips and use the stock provided compiler.

looks like IDE 1.5.7 BETA, has just upgraded both AVR-GCC and AVR-DUDE to the latest. Which include support for both m328 and m328p or above mentioned Steps 1 and 2. Step 3 is still needed.