text:
Arduino Uno Gravitech Rev 3.0 with avrdude CLI (Mac OS) - Is my script correct?
I am dealing with an Arduino Nano board rev 3.0 from Gravitech.
There is a program inside that I'd like to download to a HEX file. Thus I can upload it to other Arduino Nano boards.
I'm a newbie with Arduino. Therefore I've read much documentation on the internet and I came to the point to use avrdude in the command line as Arduino IDE does not provide a feature to perform a download to an HEX file (as far as I've understood).
I've installed all the necessary software on my Mac OS Mojave (avrdude v7.0 using 'Mac Ports'). And after powering up and connecting the Arduino Nano board to a USB port of my Mac, I launched the following command line:
avrdude -p m328p -D -c arduino -P /dev/tty.usbserial-A9077L99 -U flash:r:programme_arduino.bin:r -v -x attempts=4
I obtain the classical message

stk500_recv(): programmer is not responding

I've noticed that the 'Rx' led and the 'L' led were blinking during the attempts.
From your perspective, do the options look good (-p -c ...)?

Thank you jsotola for your comment. Arduino IDE allows to upload a sketch to the Arduino board. The command line utility 'avrdude' should allow to download the Flash ROM content of the Arduino board to a hex file or binary file. Correct in my command line I put 'programme_arduino.bin' instead of 'programme_arduino.hex'. However I think it doesn't make a difference.

I add a precision, I used 'programme_arduino.bin' based on the settings I found on the website https://www.evilmadscientist.com/2011/avr-basics-reading-and-writing-flash-contents/

my apologies, I misunderstood what you are asking ... start with a blank Arduino Nano and the Arduino IDE ... in settings, turn on show verbose output during upload ... upload an empty sketch to the Nano ... the Arduino IDE will display the avrdude command line that is required to upload a sketch ... then edit the command line to do a download instead

show verbose output during upload sounds a good hint to get a good reference for my command line. However as I don't want to overwrite my existing code, I've tried this setting with my board disconnected. Arduino IDE does not display the command line as no port is connected.

Your first problem is the no-response complaint. You said "I've noticed that the 'Rx' led and the 'L' led blank during the attempts." Is "blank" a typo (i.e., the LEDs do blink?) or did you mean they do nothing? Are you using the same cable you used to program the nano? Can you swap with another cable? Test this cable with another nano? Is the port ID typed correctly (/dev/...etc)?
Double-check the programmer ID (-c option) and part number (-p option) by querying AVRDUDE (specify '?' instead of a valid value on each of those).
For the -U option, you'll want to name the output file with a .hex extension, and specify the file-format as 'i' for intel hex:
-U flash:r:programme_arduino.hex:i
Here is the AVRDUDE reference I used.
Update:
I agree that your port ID must be correct and the cable is working, since your LEDs are blinking. But you get an error message about "not responding". Does the Nano have a bootloader in it? Could the boot-loader have been damaged when you uploaded the code (e.g., the code is large enough to over-write some of the bootloader)?
Is binary code in the Nano the only copy, or do you have the source code for it? If you have the source, you can recompile it (if necessary) and retrieve the resulting .hex file. Would that solve your problem? By setting the IDE to produce verbose output, you'll see the path to the temporary files, including the .hex file. Then use Finder (or a Terminal command, if you are comfortable with that) to copy that temporary .hex file to someplace safe.
Update 2:

Are bootloader ROM area and Flash ROM area two different memory areas?

Not separate - the boot-loader is placed at the top of Flash. It is possible for a large enough program to over-write it - I'm not sure whether that has to be specifically allowed, such as by setting fuses. If it does get over-written, it obviously becomes unusable.
I wonder if the flash can be read using a hardware programmer? Do note that these chips have lockout-fuses that can be set to prevent further programming or reading of the flash.
Since the code in this device seems valuable to you, I would suggest putting this Nano board aside, and only experiment with another, hopefully identical, board. On the new board -

Upload a sketch to it;
Copy the AVRDUDE command line used to by the IDE to upload it, and modify it as you've already described. Of course, this command will already have the board-specific parameters;
Use the modified command to download the sketch to another file, and compare it to the file that was just uploaded.

Once you can do this successfully, apply that last step to copy the sketch from your valuable Nano, then put that board away again. Load and test the downloaded code on your experimental Nano. Don't forget to include the valuable Nano's EEPROM - it might contain some critical data.

About 'blank' I wrote it incorrectly (excuse my English I am French ;-)). I meant 'blink' i.e. the led is blinking during the avrdude attempt.

I tried with 2 mini-B USB cables. The behavior is strictly the same. To notice that those cables are not original ones delivered with the Arduino board.

I have only one Arduino Nano board. I can not try with another one.

I consider the port ID is typed correctly as during the avrdude attempts I see the leds blinking (Rx, L). It means there are some data going through the Arduino USB Rx line at least...

About the programmer ID (-c option), here is something I don't understand well. I have a doubt about the one to choose, 'arduino', 'usbtiny', ... I keep 'arduino' as I have a bit of communication with it at least...

About the part number (-p option), I initially use 'm328p' (value given when I tried to use Arduino IDE). However, now looking at the schematic of the Arduino Nano from Gravity, I see the microcontroller 'ATmega168' is used. So I assume I should use 'm168' by the end...

About the memory operation (-U option), I used the setting from the following website: https://www.evilmadscientist.com/2011/avr-basics-reading-and-writing-flash-contents/. Reading it again it is about downloading a raw binary format.

Thank you @JRobert for your update: the binary code in the Arduino Nano is the only copy I have. I don't have the source code unfortunately (the guy who made it left a long time ago. Therefore there is no way to recover the source code).

Good question about the boot-loader. The code is running as I can interact with the  overall electronic as expected. Are bootloader ROM area and Flash ROM area two different memory areas? I.e. a .HEX file coud be uploaded overlapping both bootloader ROM area and Flash ROM are?!


text:
Arduino Uno R3 assembly code to push a button and turn on a LED
I've been trying this for days without success...
I need to turn on a LED on portb when a button in portd is pushed. Cabling works, I've tested it with Arduino IDE and it works like a charm.
This is what I got so far:
.global main
.equ LED, PB5
.equ BUTTON, PD3
main:
   ldi r22,0xff                    ;all bits in portb are output
   out _SFR_IO_ADDR(DDRB),r22
   ldi r21,0x00                    ;all bits in portd are input
   out _SFR_IO_ADDR(DDRD),r21
   ldi r19, 0b00000000             ;unpushed button
   ldi r18, 0b00100000             ;pushed button
   eor r16, r16
loop:
   out BUTTON, r16                 ;read button to r16
   cp r16, r18                     ;compare r16 with r19 (button on)
   cbi _SFR_IO_ADDR(PORTB),LED
   breq loop                       ;go back to loop
   sbi _SFR_IO_ADDR(PORTB),LED     ;if z=1, turn led on turn led on
   rjmp loop                       ;back to loop

It is much easier with sbis, if I got it right...
#include <avr/io.h>
.equ LED, PB5
.global main
ldi r16,0xff
out _SFR_IO_ADDR(DDRB),r16
ldi r16,0x00
out _SFR_IO_ADDR(DDRD),r16

main:
    sbis portd, 3
    rjmp ledoff
    ldi r16,0xff
    sbi _SFR_IO_ADDR(PORTB),LED   ; turn on led
    rjmp main
ledoff:
    ldi r16,0x00
    cbi _SFR_IO_ADDR(PORTB),LED   ; turn off led
    rjmp main

But I got this error compiling:
.pio\build\uno\src\main.o: In function `main':
(.text+0x8): undefined reference to `portd'
collect2.exe: error: ld returned 1 exit status
*** [.pio\build\uno\firmware.elf] Error 1

This line:

   ldi r18, 0b00100000             ;pushed button

does not match the definition of BUTTON. You are setting bit 5 of
the register, whereas the button is on bit 3. In order to avoid
this kind of error, I would rather write
   ldi r18, _BV(BUTTON)            ;pushed button

Then, here:

   out BUTTON, r16                 ;read button to r16

you are not reading anything: you are writing somewhere. I guess you
mean:
   in r16, _SFR_IO_ADDR(PIND)      ;read button to r16

Note that this reads the whole port at once. If you are only interested
in one bit, you should then
   andi r16, _BV(BUTTON)           ;keep only the relevant bit

before the comparison.
One last thing: you may want to read about the sbis and sbic
instructions: they could simplify the code you have here.

Edit: answering the updated question.

undefined reference to `portd'

This is because there is no such thing as “portd”. You mean
_SFR_IO_ADDR(PORTD). Well, no, you should actually use
_SFR_IO_ADDR(PIND), as this is the port input register, whereas
PORTD is the output register.
A couple of extra notes:

Do not put code before main: it will not be executed, as the C
runtime jumps to main after its initialization.
The instructions ldi r16, … within the main loop serve no purpose:
you are not using this register after the program initialization.

source: Stack Exchange

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

sort: votes


text:
What wrong with my Arduino code?
I have a rotary encoder (ppr = 600) and I want to write code to achieve the implementation to read current angle and direction.
Here is my code. I think it is correct but it donot have any output on the serial monitor.
#include <Servo.h>

// Rotary Encoder Connections
int encoderPinA = 2;  // Connect the CLK pin of the encoder to digital pin 2
int encoderPinB = 3;  // Connect the DT pin of the encoder to digital pin 3

// Variables
volatile int encoderPos = 0;   // Current position of the encoder
volatile int lastEncoderPos = 0;  // Previous position of the encoder
int clockwiseSteps = 0;  // Total clockwise steps turned
int counterclockwiseSteps = 0;  // Total counterclockwise steps turned
int latestOperation = 0;  // Latest rotation operation (1 for clockwise, -1 for counterclockwise)
int degreesPerStep = 360 / 600;  // Degrees per step for a 600-pulse rotary encoder
int aLastState = digitalRead(encoderPinA); // Default state of Pin A

void setup() {
    // Set encoder pins as inputs
    pinMode(encoderPinA, INPUT_PULLUP);
    pinMode(encoderPinB, INPUT_PULLUP);

    // Attach interrupts to the encoder pins
    attachInterrupt(digitalPinToInterrupt(encoderPinA), updateEncoder, CHANGE);
    attachInterrupt(digitalPinToInterrupt(encoderPinB), updateEncoder, CHANGE);

    // Initialize Serial communication
    Serial.begin(9600);
}

void loop() {
    // Print the total degrees turned in both directions
    if (encoderPos != lastEncoderPos) {
        int rotation = encoderPos - lastEncoderPos;
        if (rotation > 0) {
            clockwiseSteps += rotation;
            latestOperation = 1;
        } else {
            counterclockwiseSteps += rotation;
            latestOperation = -1;
        }
        lastEncoderPos = encoderPos;

        int currentAngle;
        if (latestOperation == 1) {
            currentAngle = (clockwiseSteps - counterclockwiseSteps) * degreesPerStep;
            Serial.print("CW | ");
        } else {
            currentAngle = (clockwiseSteps - counterclockwiseSteps) * degreesPerStep;
            Serial.print("CCW | ");
        }
        Serial.println(currentAngle);
    }
}

void updateEncoder() {
    int aState = digitalRead(encoderPinA); // Reads the "current" state of the outputA
   // If the previous and the current state of the outputA are different, that means a Pulse has occured
    if (aState != aLastState){
   // If the outputB state is different to the outputA state, that means the encoder is rotating clockwise
     if (digitalRead(encoderPinB) != aState) {
       encoderPos++;
     } else {
      encoderPos--;
     }
   }
   aLastState = aState; // Updates the previous state of the outputA with the current state
 }

Why there is no output? Seem like the interrupt function not working. How to fix it?

Can you add the exact type of your rotary encoder (and the link to a datasheet, if you can find it)? Because your code reads a "raw" rotary encoder, but the pin names CLK and DT in your code comment suggest that the encoder rather speaks something like SPI. Also, all variables declared outside and used inside an interrupt handler should be declared volatile. aLastState does not have this flag.

We definitely need to know the part number of the rotary encoder and a link to the datasheet, or at least more information about it.

@NickGammon I update the information in the text

@orithena I modify int to volatile int, but still not work

I just got this information from my teacher.

This is a "raw" rotary encoder with open collector output, so INPUT_PULLUP should be right. Let's debug "no output at all". Add in your setup() after Serial.begin(9600): delay(100); Serial.println("----- Hello -----");. If this is not printed on the Serial Monitor when you press the reset button, you probably have the wrong baud rate (i.e. not 9600) set in your Serial Monitor. If that works, add a simple volatile counter variable, increased unconditionally on each interrupt and printed unconditionally in each loop(). If this does not increase, there's something wrong with the wiring.

You can also remove the encoder and manually connect and disconnect the interrupt pins to/from ground. This will take the characteristics of the encore out of the equation.

Add in your setup() after Serial.begin(9600): delay(100); Serial.println("----- Hello -----"); - so what happened when you did that? Please edit the question to describe.

Your tag Arduino-Uno is completely contradicted by your photograph showing a Arduino Mega 2560. Please edit the tags and get that part right. Also, you did not mention the part number of the encoder.

Since the interrupt routine only does anything if the A pin has changed, the second attachInterrupt line is not needed.  You don't need an interrupt for the B pin if you aren't going to react to changes on the B pin.

int degreesPerStep = 360 / 600; This integer division resolves to 0. Use a float datatype instead of int. If this solves the problem then create an answer showing the code changes you made.

if (encoderPos != lastEncoderPos). This may cause sporadic problems. encoderPos is a 16 bit int. Your Mega is an 8 bit processor. If the interrupt comes during the time that this variable is read in the loop, the variable may be corrupted by the write operation in the interrupt handler. To eliminate that risk, use an noInterrupts()/interrupts() block to make a copy of encoderPos. (topic: non-atomic read operation. Note that this  is not the same as declaring the variable as volatile which signals the compiler not to retain possibly stale versions of the variable )

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


text:
Arduino and XBee Series1
I have actually reap 3 numerical values (3 sensors) from a remote XBee module and then manipulate these 3 signal with an Arduino card attached to another XBee module. To do this, I chose to use the IO line passing because it proved the easiest. My problem is this: for the XBee transmitter, I set:
ATID 3001
ATDL 2
ATMY 1
ATIU 1 / / to activate the IO option
ATD0 3 / / where is plugged a pushbutton
ATD1 3 / / where is plugged another pushbutton
ATD2 3 / / where is plugged proximity sensor (presence)

For the XBee receiver (the one connected with the arduino board):
ATID 3001 ATDL 1 ATMY 2 ATIA 1
ATD0 4
ATD1 4
ATD2 4

Where I'm stuck is on the Arduino programming. Which command is used to determine the change of state of xbee remote? because I want to know if the states of the sensors on input are high or low.

possible duplicate of communication xbee and arduino

There are two ways this could be tackled:

physically through connections between the xbee and arduino and read the xbee pins directly (I've never done this, and it comes down to your shield supporting it). Each of the desired output pins of the receiving xbee would be tied to a GPIO pin of the arduino. Alternatively,
serially using AT commands via the serial connection.

I have never worked with series one, but essentially:

setup a serial connection to your arduino
send the desired AT command requesting the pins value
read the serial port response

Make sure to read the manual for the series 1 xbees for the right AT commands and in how to interpret the results. Register at digi and download the datasheet.
Also, just realise reading the xbee data is going to be different depending on how you have the xbee setup, ie API vs AT mode.
Here is someone who has done some work with series 1: http://www.johnhenryshammer.com/WOW2/pagesHowTo/xbeeSeries1.php#index
I'll leave the actual implementation to you since this sounds a little like a homework assignment. Give it a go using the second method above and see how you go. Then post back here (ie update the question) including source code and exact layout (schematic preferred) and we'll see where we can help you from there.
Hint: google such terms as: "read data pins xbee arduino" (without the quotes).

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


text:
Bredboard board in new release
I had installed the old release (1.0.5) but for some reasons arduino stops working and I upgraded to new version 1.8.2, all works fine but I would like to use the bredboard 8Mhz version in the new release, but the boards system is not compatible with new version. The boards.txt is this:
##############################################################

atmega328bb.name=ATmega328 on a breadboard (8 MHz internal clock)

atmega328bb.upload.protocol=stk500
atmega328bb.upload.maximum_size=30720
atmega328bb.upload.speed=57600

atmega328bb.bootloader.low_fuses=0xE2
atmega328bb.bootloader.high_fuses=0xDA
atmega328bb.bootloader.extended_fuses=0x05
atmega328bb.bootloader.path=arduino:atmega
atmega328bb.bootloader.file=ATmegaBOOT_168_atmega328_pro_8MHz.hex
atmega328bb.bootloader.unlock_bits=0x3F
atmega328bb.bootloader.lock_bits=0x0F

atmega328bb.build.mcu=atmega328p
atmega328bb.build.f_cpu=8000000L
atmega328bb.build.core=arduino:arduino
atmega328bb.build.variant=arduino:standard

How to build it to be compatible with news version? Thank you

try adding atmega328bb.build.board=Bredboard as Arduino IDE 3rd party Hardware specification seems to say it's needed for boards on the IDE board menu

I wrote: atmega328bb.build.board=AVR_ATMEGA328BB

I found a solution in this video:
https://www.youtube.com/watch?v=cebMSJrNntI
Adding:
##############################################################

atmega328bb.name=ATmega328 on a breadboard (8 MHz internal clock)

atmega328bb.upload.protocol=arduino
atmega328bb.upload.maximum_size=30720
atmega328bb.upload.speed=57600

atmega328bb.bootloader.low_fuses=0xE2
atmega328bb.bootloader.high_fuses=0xDA
atmega328bb.bootloader.extended_fuses=0x05

atmega328bb.bootloader.file=atmega/ATmegaBOOT_168_atmega328_pro_8MHz.hex
atmega328bb.bootloader.unlock_bits=0x3F
atmega328bb.bootloader.lock_bits=0x0F

atmega328bb.build.mcu=atmega328p
atmega328bb.build.board=AVR_ATMEGA328BB
atmega328bb.build.f_cpu=8000000L
atmega328bb.build.core=arduino:arduino
atmega328bb.build.variant=arduino:standard

atmega328bb.bootloader.tool=arduino:avrdude
atmega328bb.upload.tool=arduino:avrdude

to /hardware/arduino/avr/boards.txt

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


text:
Clear existing array when getting new serial command
I'm starting to build my first Arduino project but I'm running into some problems with serial communication.
I get serial data from the console and store it in a char array called "data".
Then, when I send a new console message to the Arduino, I want it to clear the existing "data" array and store only the new data in that array.
I don't understand exactly what's wrong with my code: I believe those nested Serial.available() statements don't work but I have no ideas on how to fix the code.
Data is correctly stored by the Arduino but it concatenates the newer string to the old one.
int count = 0;
char data[30];
boolean dataComplete = false;

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

void loop() {

  if (Serial.available() > 0){
    if (dataComplete == true){
    Serial.println("There is data already, clearing...");
    char data[30];
    dataComplete = false;
  }
    if (dataComplete == false){
      Serial.println("New command, collecting...");
      while (Serial.available()>0){
        char character = Serial.read();
        data[count] = character;
        count++;
      }
     dataComplete = true;
    }
  }
  Serial.print("Command received: ");
  Serial.println(data);
  delay(1000);
}

Thanks in advance!

To clear an array you would do:
for( int i = 0; i < sizeof(data);  ++i )
   data[i] = (char)0;

or
memset(data, 0, sizeof(data));

, which does the same thing using a library function.
However, because strings of characters (not referring to 'String' objects here) are terminated by a zero byte, only the first byte needs to be zeroed:
data[0] = (char)0;

will do it.

First of all, this is an excellent example why whitespace matters. Your code is really hard to read as it is, as skimming over it, it seems as the second if statement is outside of the first one.
Fixed code:
int count = 0;
char data[30];
boolean dataComplete = false;

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

void loop() {
  if (Serial.available() > 0){
    if (dataComplete == true){
      Serial.println("There is data already, clearing...");
      char data[30];
      dataComplete = false;
    }
    if (dataComplete == false){
      Serial.println("New command, collecting...");
      while (Serial.available()>0){
        char character = Serial.read();
        data[count] = character;
        count++;
      }
     dataComplete = true;
    }
  }
  Serial.print("Command received: ");
  Serial.println(data);
  delay(1000);
}

Also, it seems as it prints "Command received:" every iteration, regardless of if there's new data or not (although, this could be the intended feature).
Like mentioned, you don't clear the variable, you just create a new one. You'll need to clear and reset count to fix this issue. However, just resetting count won't work if the second command is shorter than the one before.
Also, why do you complicate the code with the dataComplete variable? I simplified the code below:
int count = 0;
char data[30];
boolean dataComplete = false;

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

void loop() {
  if (Serial.available()){
    Serial.println("New command, collecting...");
    count = 0;
    data[] = "";
    while (Serial.available()){
      char character = Serial.read();
      data[count] = character;
      count++;
    }
  }
  Serial.print("Command received: ");
  Serial.println(data);
  delay(1000);
}

This probably doesn't do what you intend it to do:
Serial.println("There is data already, clearing...");
char data[30];

Your output says you are clearing the data array, but you're doing no such thing. In fact, you are declaring a new local variable called data, which is independent of the global data you already have declared at the top of your program. Local variables only exist within the scope in which they are declared (inside their nearest enclosing { }).
Instead, your count variable keeps track of how much data you have received. So perhaps do the following:
Serial.println("There is data already, clearing...");
count = 0;

This is not the only thing that might cause your program to operate unexpectedly, but it should at least fix the problem stated in your question.

Also a null terminator is needed for data: Add data[count]='\0'; after dataComplete = true;

Yes, that's true, but the larger problem is that there is no way for the sender to indicate the end of a data transmission other than to pause. And since this is serial, there is going to be a long enough pause in between every character transmitted.

Thanks to both of you guys. My code was wrong and changing it to "count = 0" worked. I also added a delimiter to indicate the end of an input command and it works as intended now. However, the only way that worked to empty the "data" array was using a for loop as indicated by @JRobert: this way newer commands work even if they are shorter than older ones.

I was read all comments on this question, but all codes was share so verbosing. After that, i create a code with simple functions and less of line. in this case, i think this code will working fine
if you set baudrate under 115200, must be add delay() for saving message to char array
void loop() {
    char data[255];
    uint8_t k = 0;
    while (Serial.available()) {
        data[k] = Serial.read();
         k++;
    }
    for (int i = 0; i < k; i++) {
        Serial.print(data[i]);
        data [i] = '\0';
    }
    //delay(50);
}

char data[] = {}; will give you a zero-length array. Trying to put data into it is a bad idea.

I agree with @NickGammon .  Please edit your answer to replace "I think... will work fine" with a definitive yes/no, once you have tested the code.

@NickGammon thanks for the correction, i was revision my code

To speak to the point of the question, and what the author was attempting to accomplish.
None of this code actually works as a whole. The data would get over written and just keep looping continuously... anyway here is a working example of the original code.
This method I prefer to clear an array:
    for( int i = 0; i < sizeof(data);  ++i )
    data[i] = (char)0;

Here is working example. ( Make sure to select Carriage Return on the serial monitor )
    char message[32];
    uint8_t incomingByte = 0;
    uint8_t BufferPos = 0;
    int clearbyte = 0;

    void setup() {
    Serial.begin(9600);
    Serial.println("\n String conversion testing");

    }

    void loop() {

       if (BufferPos >= 32) {
              Serial.print("Buffer Full\n");
              BufferPos = 00;
              incomingByte = 0;

       }

      if (Serial.available()) {
             incomingByte = Serial.read();
             message[BufferPos++]= incomingByte;

         switch(incomingByte)
      {
           case '\n':
           case ' ':
             break;
           case '\r':
              Serial.println(message);

          for( int i = 0; i < sizeof(message);  ++i )
         message[i] = (char)0;
              BufferPos= 0;
              incomingByte= 0;

      }
      }
    }


text:
Data packet format when USB initialized as COM port
Does anyone know how the data in data packet looks like when the USB is initialized as COM port?
I have a Arduino Mega 2560. I have initialized COM port with a baud rate of 9600. I know that there are four types of USB packets as

Token Packet (Commonly used for device identification and transaction initiation.)
Data Packet (Contains the data that needs to be transferred from host to client or vice-versa.)
Acknowledgement Packet (Acknowledgement for error-free data reception.)
Special Packets (Hub to hub communication and speed differential.)

The payload in data packet is formatted as
DATA1 >> PAYLOAD >> CRC16 ; DATA2 >> >> PAYLOAD >> CRC16 ; etc.
Till this point I am clear about whats happening.
Now all I want to know is

How the data is structured in the PAYLOAD section, when USB is initialized as COM port?
How the baud rate comes into picture i.e how a particular baudrate is achieved in this type of communication?
How is communication in terms of packet sequence? Does the sequence of packets change? (Like token>>data>>ack>>data>>ack>>...)

I really need to know this urgently as I am working on program that has to connect with 3 MEga2560 boards through a USB hub. I want to fix my design constraints depending on what is the maximum baud rate that I can achieve for all boards.

What you are looking for is a reference on the CDC/ACM scheme (or where applicable older vendor-unique schemes such as that of the ftdi chips).  You might find it interesting to either read the relevant linux kernel driver, some of the Android USB host code that is out there, or the firmware of the 8u2 chip.  However, normally an application would not pay any attention to this, and the let the operating system handle it.

The user-visible baud rate has no effect on the USB (which is probably 12MB/s), it is just a configuration parameter passed through for the 8u2-Mega2560 serial channel.  What you do have to watch out for on USB is latency - regardless of "serial" baud rate it can take longer than on a true serial link to a send byte or two and get a response, as the USB portion of the connection is limited to packets sent at fixed intervals no matter how small.

Once the USB connection is initialized as a COM port, it no longer utilizes traditional USB packets (only internally). It acts as a regular COM port. This layer of abstraction is created by 8u2 chip on Arduino side and by the driver on the PC side.
If you need to use the USB without the COM port abstraction, you have to probably configure the 8u2 chip to behave this way. I think it should be possible to configure to act as some HID device for example. You would also need to take care about the PC side and you might have to write your own driver.
For a guide on hacking and configuring the 8u2 chip on Mega, see following link:
http://arduino.cc/en/Hacking/DFUProgramming8U2

Can you suggest me any link where I can read more about this:- "it no longer utilizes traditional USB packets" . This would be really helpful.

The first sentence here is not very accurate.  There is no difference between initialization and operation - it is still a USB device on the wire, and a serial device to client programs downstream of the ttyACM driver (or whatever your operating system choses to call it).


text:
Sending data from Processing and receiving as uint32_t
I need to send data from a processing sketch to an Arduino to pass to a function that takes a uint32_t.  How to I send the data in Processing to be run on the Arduino

One byte at a time.

I recommend studying up on bitwise shifts (<< and >>), along with the bitwise OR and AND. They're what you're going to need, especially since atoi() would only give you a 16 bit, signed integer.
Let's say that your variable's binary is this (split up into 4 segments):
10010010 10110101 01010010 10010100

Sending
uint32_t myVarCopy = myVar;
for(int i = 0; i < 4; i++) {
    Serial.write(myVarCopy & 255);
    myVarCopy = myVarCopy >> 8;
}

The first line in the loop modifies the variable by bitshifting right eight to allow us to read the data eight bits at a time. We have to, whenever sending data through the serial port, "trim" any data that is in the 9th digit or above using the & 255 part. This allows us to split this int up into four bytes.
How the myVarCopy variable would look over the four iterations:
After 1: 00000000 10010010 10110101 01010010 (sent 10010100)
After 2: 00000000 00000000 10010010 10110101 (sent 01010010)
After 3: 00000000 00000000 00000000 10010010 (sent 10110101)
After 4: 00000000 00000000 00000000 00000000 (sent 10010010)

Reading
uint32_t buffer = 0;
for(int i = 0; i < 4; i++) {
    buffer = (buffer >> 8) | (Serial.read() << 24);
}

This code works by adding the newest data onto the digits 25-32 after it moves everything else over eight bits.
This is how the buffer variable would look over the four iterations:
After 1: 10010100 00000000 00000000 00000000
After 2: 01010010 10010100 00000000 00000000
After 3: 10110101 01010010 10010100 00000000
After 4: 10010010 10110101 01010010 10010100

Depending on how Processing works, you might have to worry about little/big endian encoding to ensure that your data is in the right order. Warning: I haven't tested these yet as an IDE isn't installed on the computer I'm typing this on. Also, I don't know the exact function calls for Processing, so it might not compile.


text:
Varying motor speed with the L293D
Im using a potentiometer to control the speed of two generic 6-8V DC motors. The potentiometer input is scaled from 0-1023 to 0-255, I then use the analogWrite() function to write this value to the enable pins on my L293D motor controller.
Im sure this should control the speed but it doesn't, I have the code printing the value it sends to the enable pins and this is correct, but no speed increase, the motors either move at one speed or don't move at all. My enable pins are 12 and 13 on my Arduino Uno, previously 5 and 6 but I moved them to see if that was the problem.
Is there a problem with the PWM frequency maybe? I don't understand why it won't go faster and slower after days of troubleshooting.. The inputs are all set correctly, allowing both motors to move in the forward direction..
int Speed = analogRead(speedChange);
int SpeedMap = map(Speed,0,1023,0,255);
analogWrite(enable1, SpeedMap);
analogWrite(enable2, SpeedMap);

Its a long shot but does anyone know enough about PWM control on DC motors to think of any things I may be missing while trying to do this? Ill provide any info ASAP, thanks

Pins 12 and 13 on the Uno aren't PWM capable.

Thanks! You put me on the right track.. I plugged them back into 6 and 7 and I had a new set of problems.. Then I switched enable 2 into pin 5 instead of 7 and it works! Not sure why pin 7 is a bit dodgy unless that dose have pwm either

The pins that have PWM available are marked with a ~ symbol.  On the Uno that is pins 3, 5, 6, 9, 10 and 11.

@Majenko, you should put that as an answer

Although I am still figuring things out, but i hope the following things help:
http://www.solar4rschools.org/sites/default/files/robotic-sunflower-lesson4-handout4.pdf
The problem, as far as I think is that the enable pins are the ones which are supposed to help you control the speed. Please connect them to the PWM ports on your Arduino/any other device you may be using for your project.
Or, you can simply write a code which keeps on disabling and enabling the enable pins to get the desired speed (that's what PWM is supposed to do but you can try it this way, at least).

I guess you're not using the designated PWM pins provided on the Arduino Board, anyhow I suggest you read this instructible: http://www.instructables.com/id/Arduino-DC-motor-speed-and-direction-L293D/step2/L293D-Pin-Layout/ ,Perhaps this can help you in making proper connections and also help you with the code :)


text:
Using L239D with a joystick
Im making a small, controllable toy car. Im using the L239D motor controller to drive 2 6V DC motors, which I intend to control with a joystick. Using the L239D state table (shown below), I can make the car move forward, backward, left and right.
Thats all good, but I want the car to do all the bits in between those movements (drifting slightly left/right etc depending on joystick location). So far I have two separate functions that look at the x-axis and y-axis value from the joystick, scale them and apply a pwm signal. This works fine when only one function is on but ofcourse, they overwrite each other.
My idea then was to create a variable that takes the displacement of the joystick in both axis and divides them, this will be the duty cycle. I then have a delay at the end of each loop which is sized by this duty cycle. The only problem is that the motor stutters a lot and it dosent work very well at all.
I was wondering if anyone has a better idea for getting full motor control with the joy stick rather than the simple block movements (full right, full left, full forward, full backward). Thanks!

Please look at the chip on the driver board and verify the number on it.  The usual L239 is a diode, while the usual L293 is a driver (with 4 half-H-bridges, making 2 H-bridges).  If the chip is indeed L293 instead of L239, please edit your question and fix the number all thru.

Ah sorry, Im pretty sure out of the two people could guess what I'm on about anyway just through common sense

Did you look at the chip and figure out the number?  Please fix the question if the question is wrong.

The problem here is that you lack the concept of speed with your motors.
It's not enough to turn the motors on or off in the right direction, you have to control the speed of them.
Your left/right control is fine as it is (without the delay in your loop), which is controlled by the inputs being either on or off to define the flow of current through the motor.  Now all you need to do is control the speed of the motors while they are in those states.
Fortunately there is another pair of inputs to the driver chip that you have completely overlooked: ENABLE1 and ENABLE2.  These can accept a PWM signal and define the ratio of on-to-off for the motor on that channel.
So you can connect a PWM signal to each of those inputs (all the other inputs are just straight digital ON/OFF signals), and setting the duty cycle of those PWM signals defines the speed of the motor (0 = stop, 255 = full speed).
Now all you need to do is interpret the joystick properly, for instance:

Between centre and half-left: Left = Stop, Right = Forward, Enable Right = percentage of half the joystick range
Between half-left and full-left: Left = Reverse, Right = Forward, Enable Right = 100%, Enable Left = percentage of half the remaining joystick range

And of course reversed for right turns.
You could incorporate into that the forward/backward position of the joystick to add an overall forward or backward speed to the motors so you have full 2D motion.
It may be better to visualise the joystick in Polar space instead of simple Cartesian space.  Convert the X/Y coordinates of the joystick's position into an angle and distance from the centre point.  The distance defines the overall speed, and the angle defines how that speed is split between the left and right motors (enable pins), and the direction of those motors (input pins).

Brilliant. You knew exactly where I went wrong. I decided to create a series of if statements with flags that dictated which pins to set digitally. I then created a value that was the maximum displacement of both axis (0 to 255, whichever axis is bigger) and applied that value as a PWM signal to the enable lines. Works perfectly!


text:
Sending joystick data via bluetooth
Joysticks usually have two outputs, one for the x-axis and one for the y-axis. Most of the bluetooth modules I have found only have one tx line.. Is there a way to set them up to use one bluetooth module to connect to arduino?
Im thinking of buying another but I'm wondering if anyone has a better idea than this, or if what I'm thinking is even possible.
Thanks!

What joystick? What bluetooth module?

Unless you have a very special joystick and a very special bluetooth module you can't just connect a joystick to the TX pin of a bluetooth module.
Instead you have to have the joystick (I am assuming a 2D analog joystick) to a pair of analog inputs on (for instance) an Ardiuno, which then samples the analog values.  It is then up to you to decide what you do with that sampled data - in your case you want to send it out via serial to the bluetooth module (I assume something like a HC-05 or HC-06).  What that data is, and how you interpret it, is up to you.
You could send the data as plain text, such as:
512,512
512,512
384,512
229,512
83,512
83,938
82,1012

Each line specifies a pair of analog values and is terminated by a line-feed.  The receiving end then needs to read each line, split it on the ,, and interpret the two values as X/Y readings.
That's quite inefficient, though, and there are better "binary" methods that use less bytes to send the readings, but that is more advanced.

So your joystick is sending bt signals?
If you can't find an appropiate data sheet to that i advise you link it with your pc, start hterm and analyse what exactly is sent.(requires to link the bt devices)
If your joystick is not able to out bt signals I'm not sure what you are trying to do there and need more info
PS: I already did the following: control a robot with your smartphone via bt
control a robot with an old ps2 joystick via cable


text:
Arduino can't multiply?
I have a value I'm taking from a sensor module, which is 2500 when the sensor is facing a light source. This reads to my code and can be saved perfectly fine. When I try to find the weighted average of a set of values (2500*1000+2500*2000+2500*3000 etc), the Arduino comes out with very weird answers. For example
2500*1000=9632
If I just compute 2500*1000 on its own, the answer still comes out the same! The results come out negative if I use int so I switched to using double (just in case the values created were too big), this stops producing negatives as expected but the result is still like it is above.. I have no idea why.. any ideas?

Fixed it! The problem is that if you multiply a double by an int it turns into an int... I was using doubles for everything but then my weight was using the counter variable, i (e.g. 1000*(i+1)).. This turned the end result back into an int!

No. double × int → double. Actually, “doubles” are just floats on Arduino (32 bit, i.e. single precision).

Hmm, but then why did this happen:
val(double)weight(double)(i(int)+1) = the integer result and not the double?
Even though it was stored in a variable defined as a double.. Im trying to describe the problem in a way that will help people stuck with the same issue because this had me confused for ages

Show your code -- it could be how the results or intermediate results are stored.

for (int j = 0; j < NUM_SENSORS; j++)
{
sensorTotal+=sensorValues[j]; //This works
sensorWeighted+=sensorValues[j]1000(j+1); //This dosent
}
problem fixed by casting the j inside (j+1) to a double.

Makes little sense to me. If sensorValues[j] is int, (sensorValues[j] * 1000) will be computed as an int, no matter what you have in the next multiplication. You should probably show a little more of your code (at least the relevant declarations with the types). Add that to the question, indented by four spaces.

(2500*1000) % 2^16 = 9632

2500 * 1000 = 9632 is exactly what you expect with 16-bit integers. You
should use long integers instead:
2500L * 1000L == 2500000L

Floats work also, but are more expensive:
2500.0 * 1000.0 == 2500000.0

although I do not recommend testing for exact equality of floats (it
works here because these numbers are exactly representable).


text:
Using multiple laptop battery packs to power everything
I'm working on a medium sized robot project with multiple arduinos to control stuff. I've been planning on using a lead-acid battery pack, but then I was given 10 working and identical Asus laptop battery packs rated at 14.8 V 4400 mAh, and one old Asus laptop.
I opened up one of the battery packs, because it was bad and it has a 4S2P battery configuration and a protection board.
Can I hook all of these battery packs in parallel, or will power leak between the battery packs, and is that be a problem?
Is there alternatively some 4S20P or 3S25P battery pack with charger I can purchase to put these batteries in?
(I do have a step-down converter that will provide the Arduinos with the right voltage, regardless of input voltage up to 36 V)
I tried to ask a similar question on electrical engineering, but ot was deemed off topic for the site.

Doesn't sound off-topic for EE.SE to me...

@IgnacioVazquez-Abrams The question was put on hold, and I deleted it. They said the site was about design of electronics, not usage of electronics.

A power source is electronics.

You mentioned that you have several Arduino for your robot, hence I deduce you probably have several actuator devices (those that need high current), so why not use each battery as a distinct power source? If needed, you'd just have to connect all grounds, but they would not be used in parallel.

@jfpoilpret I could do that, possibly. I've also considered using relays to switch between power packs. Ideally, I want the robot to be "self contained" with a single 220V wall socket connector for charging. The Arduinos are for sensors mostly, Raspberry Pi for logic; it will have a web server, rotating IR radar", two wheels (balancing), speed sensors on the wheels, temperature sensor, whatever I can come up with.

Sometimes I think EE.SE is suffering from overzealous moderating.. I hope Arduino.SE remains as open as it has been.

What's worse, is that when EE.SE flushes sound engineering-principles questions elsewhere, they often get answers of a lower quality.

In case you didn't know it already you can hook any batteries in parallel by adding a diode on every battery to avoid current from any other battery flowing back to it. Like this:
 battery
      |+  diode
+----||--->|---+
|     |        |
|              |
|     |+       |
+----||--->|---+----o V++
|     |
|
_
V GND

The drawback is that you have a small drop of voltage on the diodes and of course a small power loss too. If for example you're drawing 0.5 Amp from the batteries and you're using an 1N4001 diode which has a voltage drop of about 0.7 Volts then expect  0.350 Watts of power loss (0.5A x 0.7V). So choose the diode with the lowest voltage drop that can handle the current you need. There are solutions to lower the power that is wasted but they're more complex.

What happens if I have different voltages on the batteries? A short between the different potentials?

To a first approximation, you only draw significant power from the highest voltage one, until it discharges to match another.

@chris-stratton What you're saying sounds obvious when you say it :)

I'd be cautious about hooking them in parallel. According to ADAfruit power leakage between batteries is a problem.

[multipack parallel] ... batteries are assembled by a company that is experienced and certified to test and assemble battery packs. The individual batteries are tested and sorted by machine so that each pack has matching batteries with the same capacity and internal resistance. Individuals do not have this equipment, which is why you should not try to make your own packs.

Are you certain all your batteries are the same age and have the same usage history? A brand-spanking new one will try to charge an old worn battery to its own fresh voltage.

I have two numbers about the packs; voltage at full charge (16.5V for the good packs) and a remaining battery time as reported by the PC; most are around 3 hours. A few are really bad (50 minutes or less battery time left, at full charge).

Since each battery pack has built in over- and undercharge protection, I assume any leakage between the packs will be no problem. One pack at 14.8 volts cannot overcharge another pack to more than 14.8 volts, and I will never connect an empty battery pack together with fully charged battery packs.

@frodeborli I wouldn't assume that with lithiums as the charging cycle is a bit more complex. The protection circuitry stops under and over voltage on the battery cells, but it might expect a constant, high-current source for its input. You will need to find out what that input is as well.


text:
Sound or motion activated long term battery powered Arduino
Basically, I want an Arduino to power up whenever a "creature" enters viscinity (at least within up to 3 meters).
I would really like this to be able to keep monitoring for at least 4-8 weeks, without having to replace batteries. I don't want to use more than 1 or 2 18650 Liion cells.
Couple of methods that I believe would work:

Changes in light-conditions.
Sound.
Small vibrations in the ground.

Approaches to conserve power:

Checking for changes in light at most every 30 seconds (boot the Arduino, and power off quickly).
Checking for 1 second for sound, every 10-15 seconds.
Vibrations in the ground using an accelerometer?

The ideal solution does not run the Arduino at all, unless a trigger causes it to run. When the Arduino starts, it will have to turn itself off again to resume monitoring mode.
What approach should I go for? I'm not very good with electronics, and would like to avoid configurations involving transistors, resistors and so on - unless stricktly required.
Is it possible/easy to wire an Arduino Pro Mini to run directly off a 3.7 V battery, bypassing any power hungry voltage regulators?

Is this a counter device you are seeking to construct? What will the arduino perform once triggered by creature and powered on?
Is it practical to consider a solar charging system as an add-on, to keep your selected battery healthy during the desired period?

Many MEMS accelerometers can be programmed to generate a wakeup interrupt to a host MCU when a threshold is exceeded.  In terms of power savings, you will need care to both hardware and software design.  The simplest conservative power solution is indeed to run directly off the cell with no regulator losses, as that is in the allowable range for your MCU - but it may not be for the MEMS.  Greater efficiency would be a well chosen switching regulator running the electronics near their minimum suitable voltage where consumption will be lowest.  Watch out for voltages left across resistors!

I'd just go with a PIR sensor. I have my arduino check light levels every 250ms, and it runs for more that half a year on 2 AA batteries.

For a truly low-power, Arduino-based, solution the following it's needed:
A) HARDWARE SIDE:

Use a supply voltage and clock frequency as low as possible. The Arduino Pro Mini 3.3V @ 8Mhz board is a good starting point for a first project.
Get rid of all the LEDs in the board. Their consumption is in the mA range, way too high.
Get rid of the onboard regulator and replace it with a low quiescent current, low dropout regulator like the MCP1700. You don't need a switching regulator unless your Arduino spends most of the time awake and consuming a lot of current, which is a very unlikely scenario. The high quiescent current of switching regulators rules them out for this kind of applications.
Select a low-power consumption sensor and signal conditioning circuitry. PIR and CMOS logic family 74HC are good technologies for this.
The signal conditioning circuit must generate a level interrupt from whichever signal is delivered by the sensor. Timing elements (like capacitors) may be required for this. To be on the safe side, design it for a 100 ms resettable pulse.

B) SOFTWARE SIDE:

Install a low power Arduino library like this one. Use the ATmega328p power-down sleep mode.
Write a interrupt service routine (ISR). This is the piece of code  will deal with whichever needs to be done upon an interrupt event.
Configure the interrupts as required. Note that only level-triggered interrupts can wake up ATmega328p from power-down sleep mode, as per its datasheet:

Here you can find really good information on the way to go low power.

What you want to do after the triggering is an important part of this design.
An Arduino platform is not necessarily the best choice for power sensitive applications.  You identified one problem in your post: Linear regulators.  What you are likely wanting is an efficient switching power supply to support a wide range of voltages as your batteries drain.
Many embedded processor have low power modes.  Some are specially designed to reduce current draw down into the nA range when idle or sleeping.  However, all such processors require special care when configuring for these deep sleep modes.  That is to say, the application plays an important roll in deciding how to put a processor into such modes.
Supporting hardware is perhaps the most important aspect of a low power designs.  Contributions from the most advanced low power processors can be wiped out if supporting hardware runs at mA ranges.  A simple 10K pull up resistor will draw 0.5mA in a 5 volt circuit. The impact is meaningless in a mains powered application.  But for long term battery operation is could means days of lost time.
All that said, there are resources for Arduino low power operation.  Here is a low power library.  You will have to decide if it is sufficient for you application. Or if you need to also investigate low power hardware solutions.

Rechargeable lithium batteries have great energy density but they also have some significant self-discharge, making a bad choice for low-power applications. Have a look on this Arduino "clone": https://talk2.wisen.com.au/product-talk2-whisper-node-avr/, which is designed to run from standard Alkaline batteries and consumes very little (under 4µA when sleeping).
For the sensors, you should look for smart ones. You can find some very sophisticated MEMs sensors which will produce interrupt based on thresholds. You normally use I²C interface to talk to those little devices.
For example, you could use something similar to this one for light sensing: http://www.vishay.com/optical-sensors/list/product-83462/. Although this is a proximity sensor, it also has thresholds for the ambient light as well as consumes very little current.
The most important is to design the solution to run at lower voltage (3.3V instead of 5V) and also use interrupts to wake-up everywhere. If you like to run a bare ATMega328p directly from a 18650 cell, make sure everything will be ok to run from 4.2V to 3.0V as you're not using any regulation.


text:
Use Higher Resistance Than Instructed in a Circuit
I'm following the "Get Started with Arduino" Guidebook, and I'm at the part where pulse width modulation (PWM) is discussed.
The instructions say to create a simple circuit with a breadboard, red LED, arduino (connected at pin 9 and ground) and a 270 ohm resistor. My power source will be the usb connection.
I have a 510 ohm resistor.

May I use it instead?
In general, will using a resistor with a higher resistance than intended in a circuit fry the arduino?

Thanks very much for your help. I'm new to arduino and electronic circuits. I have a Uno R3.

You'll need to show a schematic of the circuit. Not everyone has that book.

Thanks Ignacio, my question was answered below but I'll try to include schematics with my future questions.

The cases where using a higher value resistor will damage a circuit exist, but are a bit less usual than the cases where it may simply produce a weaker result than desired, or a different frequency response than desired.
The primary situations where you do have to watch out come about where "feedback" is used to adjust one thing in relation to something else, and so putting a larger resistor on the "sense" side of the circuit can cause the "output" to be too high.  Examples you might run into would be adjustable voltage regulators (obvious potential for damage with wrong output) and op-amps (higher than desired output, though more often distortion than damage).
It seems quite likely the the role of the resistor in your circuit is to limit the current through the LED - protecting that (and to a more vaguely best-practices degree, the ATmega pin) from damage.
For your needs it could be worth noting that a parallel combination of two 510 ohm resistors will give an effective resistance of half that, or 255 ohms.  This is very close to the design intent, so might be a decent substitution (cheap resistors have a larger tolerance for piece-to-piece variation of value than that anyway).
Normally I would say the desired 270 ohms feels a little small, and that I'd prefer to start with 330 ohms.  But if you do parallel two 510's, the 255 ohms would give just under 20ma of current if connected directaly across a 5v supply.  Given your LED will have some forward voltage drop (varies widely with color), and your Arduino pin a little of its own, the actual voltage and thus current will be less - as a guess the end result is likely to be in the 15ma range, and not unreasonable for many common LEDs.
Resistors would also be a fairly easy component to salvage out of old electronics - the leads will end up short, but other than that you basically just need to read the color code, and perhaps confirm the value after removal with a meter.
Ultimately though it is worth buying an assortment of resistors - the 1/4 watt size are generally preferred for breadboarding as the leads are the best fit.

The question specified a red LED, so the forward voltage drop is likely to be around 1.8V.

If the resistor is in series w the LED, it'll just be about half as bright when you use 510 vs 270 ohms. I=E/R and all -> half the current. Your PWM will still work, but starting from a lesser brightness on down.


text:
How to use an PCF8574P with the simplest code possible
i'm having few PCF8574P which i want to use with my arduino and multiplex them however i have no idea how to use the I2C BUS and the IC in general. There are few libraries but they're fairly complex. Is there any library which makes writing and reading from the PCF8574P easy?

Have you given Rob Tillaart's library from the Arduino Playground a try? The demo sketch might look a bit overwhelming, but at it's simplest, all your sketch should need to have to make a led blink like the standard arduino 'blink' sketch is
#include "PCF8574.h"
#include <Wire.h>

// adjust addresses if needed
PCF8574 PCF_38(0x38);  // add led to P0 (pin 4) (used as output)

void setup()
{
//your setup code here
}

void loop()
{
    //turn P0 (pin 4) of the I/O expander on and off once a second
    PCF_38.write(0, 1);
    delay(1000);
    PCF_38.write(0, 0);
    delay(1000);
}

I don't have any of these parts handy so I can only give generic advice.

This is good..simple code to blink one led. It works..I like it.
Cheers...Markus


text:
Arduino Attiny 85 IR library compiler error
I'm about to ask a question for the most common problem which everyone has with attiny85 and the IR library. I will try to make this question as simple as possible.
Few things about the lib and the chip
First of all the lib https://github.com/shirriff/Arduino-IRremote works great on the UNO and it's the best out there.
The Attiny85 is the smallest chip you can get able to run Arduino code. It has alot of limitations but it worth it!
The common problem
Attiny85 uses different timers from the normal Attiny and Atmega chips which makes it impossible to run the standard libraries. There are some fixes for some libs. For example the IR Remote has a version which ALMOST works with the chip and it can be found over here: http://gammon.com.au/Arduino/IRremote_Attiny.zip
However the problem lies in the core. The first time i used the patched IR i had the MIT High Low Media Group versino 1 of the core files which bearly worked but it was the first released so...
After reading this guide:http://www.instructables.com/id/Attiny-IR-library/?ALLSTEPS I used an updated core which can be found here: https://arduino-tiny.googlecode.com/files/arduino-tiny-0100-0017.zip
And the final problem
Even with the updated core i still got only 1 last error.
Compiling 'Shit' for 'ATtiny85 @ 8 MHz  (internal oscillator; BOD disabled)'
IRremoteInt.h:101: error: 'RAWBUF' was not declared in this scope
Error compiling

Does anyone know how to fix it?
Links

MIT high-low group first version: http://highlowtech.org/?p=1229
Tutorial for the chip and the IR: http://www.instructables.com/id/Attiny-IR-library/?ALLSTEPS
The IR original lib: https://github.com/shirriff/Arduino-IRremote
Updated core: https://arduino-tiny.googlecode.com/files/arduino-tiny-0100-0017.zip

Just in case you wanna know i'm using the Atmel Studio 6 with the Visual Micro plugin instead of the crappy-arduino-IDE

RAWBUF is defined in IRremote.h. Make sure you include that header before including IRremoteInt.h.

it worked but not im getting this:
Upload failed. Did you select the correct upload method for this board?
System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
at processing.app.debug.AvrdudeUploader.uploadUsingPreferences(String buildPath, String className, Boolean verbose, Boolean ProgrammerUploadUsing, String mcuProgrammerOverrideName)
at processing.app.SketchEditor.Upload(Boolean verbose)

That's a problem with your build environment, not the code.

Indeed. I upload it through the IDE and its working however the receiver is just dead. nothinf happens when i press the button

Keep your Visual Micro up to date and the error above will not appear :)


text:
Arduino due slow clock
To reduce the components amount I don't want to put the  32.768 kHz oscillator on my own Due.
Can I leave the corresponding XTAL inputs unconnected?
What is the main target of the slow clock?
What I can not do with the high clock but can do with the slow one?
Will I face to any issues if I don't use the low freq. oscillator?

The slow clockr is primarily used for the real time clock (RTC) module inside the SAM3X chip.  It can also be routed to other places when you want a low speed clock source, but the only places it is actually required are the RTC and the watchdog.
The slow clock can be generated from an internal RC oscillator instead of requiring an external crystal, but the accuracy and stability of the RC oscillator is many orders of magnitude worse than a crystal.  Trying to use that for the RTC module will result in the clock drifting over time.  The watchdog won't really care if the clock isn't perfectly accurate.

So I can safely go without slow clock oscillator and my Due will work.
What about the xtal pins.
Can I leave them unconnected?
I didn't find any info about that.

Atmel datasheet says:
If the user does not need the crystal oscillator, the XIN32 and XOUT32 pins can be left unconnected


text:
Arduino Due native programming port
Arduino does not recommend to program the Due board via Native port  as it is not reliable:
If the MCU crashed for some reason it is likely that the soft erase procedure won't work as this procedure happens entirely in software on the SAM3X
Unfortunately Arduino doesn't say what is crash and how to solve this issue if your home made Due has only the Native port.
I have only several assumptions but not sure that they are correct.
The Arduino Due boot-loader starts only if the Flash is not programmed. If the code is programmed to the flash but is damaged the boot-loader will not
start. As the MCU is hanged it can not erase the flash.
What can be done in this situation?
Just push the erase button on the board. It will the erase the content of the memory and allow boot-loader to start.
Now the programming via the Native port should be possible.
Please correct me if I'm wrong.

The erase pin can be configured as a GPIO. In this case pressing the erase button will not erase the flash memory.
If this is the case the hardware reset will be necessary.
Don't know yet if the erase button works together with the reset.


text:
Leonardo sketch and bootloader hex file combination
Can I combine Leonardo sketch hex file with the Leonardo bootloader hex file?
I would like to program blank Atmega32U4 with one shot.

Yes you can, and there are programs available to download that will allow you to combine .HEX files.  Ask google. The magic term is "Intel I8HEX". or "Intel HEX"


text:
Arduino DUE as a FTDI programmer
I want to use Arduino DUE board as a FTDI programmer.
The task is to program ESP32 module which is connected to the Arduino Serial port.
I can use only DUE Native port. There is no DUE programming port in my design.

Cool story dude. Why do you mention this?

Forgot to ask. Is it possible?

Yes, it is possible, and not too difficult. Also, the native port is a lot faster than the programming  port ;)
All you need to do is to read the serialUSB data in and write it to the SerialX port, and read the data in from the SerialX port and write it to the SerialUSB port. It's best to do it on a byte by byte basis, and the due should be plenty fast enough.
This code should do the job. Let me know if it doesn't, and I'll take a look. (I have a Due and esp32)
void setup(void) {
  SerialUSB.begin(9600); //speed here doesn't matter as far as I am aware.
                         //the serial baud here should match the speed that
                         //you try to upload at to the esp32
  Serial1.begin(9600);   //change the Serial port to suit your needs
}
void loop(){
   if(SerialUSB.available()> 0){
    Serial1.write(SerialUSB.read());
   }
   if(Serial1.available()> 0){
    SerialUSB.write(Serial1.read());
   }
}


text:
Arduino Requirements
I have downloaded the arduino Environment on my windows XP and also set the driver properly.
I discovered the arduino uno device on the device manager display list disappeared whenever I unplugged the arduino UNO. I want to know if there are extra things needed to set up the device as none of my sketches has ever gotten flashed to the board.
Someone told me I need Java (Compiler and Runtime) to use arduino is this true?
I only have JVR

Watch this video https://www.youtube.com/watch?v=YWY_Is0L7fE

or Watch this video
https://www.youtube.com/watch?v=4HqXAmV_Ock

I have watched the two movies Sir but it did not resolve the issue.

This is exactly what I get 'Arduino: 1.0.6 (Windows XP),  Board: "Arduino Uno" C:\New Folder\New\arduino-1.0.6\hardware\tools\avr\bin\avr-objcopy: 'Blink.cop.elf' : No such file

Are you getting an error when you program the board? What's wrong, exactly? P.S. it should disappear from device manager when it is unplugged; that is normal behavior.


text:
How to sense mobile signal coming to a room using arduino uno
How to make arduino sense mobile signal coming into a room and display the calling number on an LCD screen

So is not possible to use arduino to block a specific mobile number coming to a room before it gets to the phone and allowing  others ?

Use the configurations options of your phone to blacklist that specific number.

What you can do, if you really want your phone to change behaviour inside a certain room, is to use NFC tags, assuming the phone has an NFC reader: for example attach an NFC sticker on your nightstand, where you would usually put your phone when you sleep, and configure your phone to change profile to "siesta-time" when it touches said tag.
It's equally easy to make it go back to "Home" or "default" or whatever you like, when it unpairs from the NFC tag.

You can't.
Mobile phone signals don't respect artificial boundaries like a room's walls.  You can detect the mobile phone signal from the local cell, but you can't narrow it down to "what is talking to a device in this room".
And if you could just intercept the signals and find out who was calling whom there wouldn't be much security, would there? It's all encrypted and locked down - you can't get at that sort of information "from the air".
What you could do though, is to have your mobile phone send out the phone number of an incoming call via bluetooth (many hands free kits already use this kind of facility) and have your Arduino receive that information to display it.

So is not possible to use arduino to block a specific mobile number coming to a room before it gets to the phone and allowing others ?

Nope. You could jam all the signals in the local area but a) you'd be breaking the law, and b) you'd have people very pi**ed off coming around and smacking you up with baseball bats.


text:
Does the arduino board have to be always physically connected to the electronic device you are running?
If I have a basic electronic board with some LEDs and sound fx and I want to program them (I'm a beginner, learning about arduino), does the arduino board always have to be connected to the actual electronic board I'm running or is there a way to "upload" the programming to the circuit board?

If the "basic electronic board" is programmable, then yes, you can upload a program to it.
In general, though, "some LEDs" and similar devices are not programmable, and without something to drive them (i.e., the Arduino) they won't do anything at all.  The Arduino is what has the program and it tells the "basic electronic board", moment by moment, what it should be doing.  It is the brain of the operation.  Remove the brain from someone and you'll find their body no longer functions.

If the question is "Can I program the Arduino without anything else connected to it?", then yes, you can program it with out the sound and light board connected. But the program will start running shortly after the upload finishes.
If some devices were connected to it and some were not, it's possible the program won't function properly at that point (and obviously the not-connected devices won't function at all!), so you should make sure the Arduino can't or won't try to do anything to the few connected ones that might be harmful when some others are not connected, in case that is possible (this would be an unusual, but plausible, situation).

And Arduino UNO is basically a ATMega328 chip (with some extras) on a circuit board. So if you add an ATMega328 to your own circuitboard, you don't need an Arduino Uno.


text:
Arduino Pro Mini and GDEW0154T1 ePaper (e ink) display
I just got my Arduino Pro Mini and GDEW0154T1 ePaper display (GDEW0154T1 display) and I'm trying to figure out a way to make them "talk". I started reading documentation and multiple sites but I still have no idea. I bought Breadboard, USB connector for Arduino and cables.
I think I need some port to connect display to Breadboard. Could you tell me where to look for it? What next?
Thank you for any advice!

You need to build a special driver board.  Most of the drive circuitry is on the main chip built into the display, which is convenient, but it requires a number of capacitors (which are too big to fit into the display itself) on the various voltage pins, and a special power control circuit to ensure that the different voltages get enabled at the right time.
The datasheet details the capacitors that need connecting (Figure 7.5(2)), as well as the power control circuit (Figure 7.5(4)).
There is another small circuit snippet there as well (Figure 7.5(3), temperature sensor) but I haven't worked out the relevance of that yet.
Also you will need the right FPC connector, and a surface mount PCB to solder it on to, as well as the ability to solder it (reflow oven), so it's not a trivial task.  You may be able to find the right connector already soldered onto a breakout board if you look around - but make sure it is the right one, since there are many variations - number of pins, pitch of pins, upper or lower connection, etc.

Do you know what is component S11304BDL from Figure 7.5(4)? I can't find it anywhere.

@MattheW Any logic level N-channel MOSFET would do the job.

Thank you. Could you please help me once more? I recreated the circuit on the breadboard and I've got two doubts.

Do I connect 3.3V power to both VDDIO and VCI pins?
I look at both Figures 7-5 (2) and 7-5 (4) and I can see that VCI is on both of them. On none it is connected to 3.3V input. As far as I understand, it's connected to capacitor and ground on one side and to power control circuit on second side. Should I place 3.3V in between? Thank you for help!


text:
Motor cutting out when using HC-05 Bluetooth module
I'm using an L293D motor driver chip along with an HC-05 Bluetooth module. The two work as expected separately - I can send a string via a Bluetooth terminal app on my phone to the HC-05 and I see it in the serial monitor just fine, and I can use the serial monitor to change the speed/direction of the DC motor without an issue. However, if I try to use the Bluetooth console on my phone to change the speed, the motor only spins for about a second before I lose connection with the HC-05 and it stops.
I think this is happening because the Arduino is tripping some breaker by drawing too much current to power both the HC-05 chip and the DC motor. Is this the case? Should I use an external battery pack to power the DC motor and L293D chip, and then keep the HC-05 connected to the 5V out line on the Arduino?
Thanks.

Either that or the motor is causing EMI that is disrupting your communication.

How are you powering everything currently?

@chrisl Previously I was powering everything off of the 5V line on the Arduino, but I just switched to using an external battery pack of 4 AAs and that seems to work fine.

Will you post a scheme of your device plase? It is Hard to ubderstand What is going on without it...
As I have understood, you May have a leak of power there.. Try to power your motors using an external way: to connect them In parallel with your arduino board.
Yor problem also May be caused by that your power source is not String enough, and it May be not enough it's power to keep motirs and hc05 working at the same time.
Also, if you are using a board with severak uart pins on it, you May check if you haven't connected you motors to thise Uart pins I hooe my answer wil help you

Previously I was powering everything off of the 5V line on the Arduino, but I just switched to using an external battery pack of 4 AAs and that seems to work fine.

That suggests, that your power source was not strong enough. You didn't say, how you are powering the Arduino, but I guess you are doing so via USB. The USB port of a PC can only give you 500mA of current (at least without any extra configuration to get more). Also the parts on the Arduino (for example the diode between USB power and the 5V pin) can only give you a limited amount of current. Especially when the motor is starting, the needed current is rather big. That might have caused a short voltage dip, deep enough to irritate the HC-05 module.
Using an extra battery as power source for the motor eliminates that problem. Though I think you should be able to connect all parts to the same power source, as long as it is powerfull enough to power all parts (plus some overhead). In that case be sure to connect the power for the L293D and Arduino in parallel, so that the motor current does not have to flow through the Arduino (which could kill the voltage regulator or the diode).
Depending on your motor, it also might generate a huge amount of EMI (Electromagnetic Interference) either though air transmission or through the power lines, which might irritate the HC-05 enough. In that case the easiest option would be to add a second power source. Though I think the problem is with the power source as described above.


text:
Sonar and servo stop working when usb cable unplugged
I am using the following components to build simple motobot:

Arduino Uno
Arduino motor shield,
servo,
sonar HC-SR04,
magician chessis,
DC adapter with 4 AA batteries.

All works fine while USB cable is plugged. As soon as I unplug USB cable servo and sonar stop working, although motors connected to motor shield continue rolling.
From what I read around internet motor shield operates with 7-12V voltage. I need 5V for sonar and servo. So they both are connected to 5V pin on the shield board.
How could I overcome this issue?

Is the software on your Arduino periodically polling the sonar, or does it only ping the sonar when it gets a command from the PC through the USB cable?

@David: periodically

Sonar modules are notorious for pulling so much instantaneous power during their brief pulses that they often reset the processor, causing the Arduino to start all over from the beginning.
Do you have any way of knowing whether your program is executing more-or-less normally, or if your program in the Arduino is getting reset?
If not, you need better debugging tools.
(tangential rant about debugging tools)
Many people debug by sprinkling their code with print(F()) statements that get sent to a LCD screen or a serial port.
Other people debug by sprinking their code with statements that turn on and off a series of LEDs of various colors, or at least a single LED with a (hopefully easy-to-decode) blink code.
Some kinds of problems are much easier to track down with an oscilloscope.
dealing with high-current pulses
My best guess is that the sonar is pulling very brief high-current pulses from the battery, which causes the battery voltage to droop low enough to reset the Arduino.
When the USB cable is plugged in, (I'm guessing that) the additional power supplied by the USB cable somehow keeps the Arduino from resetting.
Many sonar modules (very briefly) pull 1 A or 2 A, far more than a USB cable or a handful of AA batteries can supply.
There are many ways to solve that problem, but if I were you I would first see if that is really the problem in this case.
Possibly the quickest way to tell is:

Use at least 2 separate battery packs.
Hook all the grounds of all the battery packs and all the devices together.
hook the positive power of one battery pack to the Arduino and nothing else.
Hook the power lead of all the other devices to some other battery pack (ideally a different battery pack for each device).

Then run the test again.
This should give you a clue as to whether the problem is the Arduino seeing power-supply droop (which separate battery packs should "fix"), or something else.
If the problem really is power supply droop, there are a variety of ways to fix it:

(a) Many people recommend: use a large 1000 uF capacitor directly across the power pins of the sonar, and a 10 Ohm or 100 Ohm resistor between the battery positive and that capacitor. (a) (b) (c) (d) (e) (f)
(b) Use a large capacitor directly across the power pins of the Arduino, and a diode from the battery to that capacitor so that normally the diode allows the battery to charge the capacitor, but when the sonar or whatever briefly drags the battery voltage to a low level, the diode blocks the sonar from pulling energy "backwards" out of that capacitor, and the capacitor is large enough to run the Arduino during the sonar pulse.
(c) Get a dedicated "logic" battery array to power the Arduino and a few LEDs, etc., and a separate (often much larger) "dirty power" battery array to power the sonar, motors, etc.

Add an extra 2-4 AA batteries in series. 4 x AA is 6V for fresh batteries, 4V when the batteries are at the end of their life, which is not enough.
An alternative is to get a boost converter, e.g. this, so you can supply 5V with less than 5V.

fresh set of batteries don't solve the problem

Not a fresh set, more batteries. You need more voltage unless your DC adapter has a boost converter.

Because I use nodejs with help of johnny-five library I asked the question on the project wiki. This is the answer from Rick Waldron:
You can't unplug the USB, doing so kills the communication between the program and the board. Those components that continue functioning only do so b/c they are still receiving power. To free the bot from tethers, check out the guide at the bottom of this page: https://github.com/rwaldron/johnny-five/wiki


text:
Where can I find out how to make a hex file for arduino firmware?
I have followed this tutorial on flashing my Arduino R3 to turn it into a "USB keyboard", but the article doesn't explain how the hex works, it's just for granted. Where can I learn about how to make my own hex file so that I can learn how to make my Arduino mimic any USB device?

Welcome to Arduino SE! You're really vague here. USB devices are a really complex topic, and most likely, you won't be able to make your own files for USB without a bit of skill. You can find HEX files for the USB chip to mimic other devices pre-compiled.

@AnnonomusPenguin Hi! I don't think any hex to imitate a DataLocker or IronKey device exist yet, so I'd like to try and do it. xD Any advice on where to start?

I don't really have any idea :D I'd say maybe look at some open source hex files that incorporate USB mass storage (I've seen a couple of open source projects with at least thirty types of USB devices for Arduino) and modify it so it doesn't show files until there is a text file with the password on the root of the device. The IRC would be a good route to get help with this. So you don't make people mad, try to learn how to do it, not just copy & paste. Also, if you do, make sure to share your code with others.

The very tutorial you are following contains links to a gzipped tar archive of the source code and makefile used to produce Darran's keyboard hex file which you loaded: http://hunt.net.nz/users/darran/weblog/b3029/attachments/bd341/arduino-keyboard-0.3.tar.gz

It is possible, but it's kind of hard(especially if you want to mod both the 8u2 AND the 16u2. I'd recommend the Teensy(https://www.pjrc.com/teensy/index.html) I recently posted a question about a question similar to yours and after hearing about all the pitfall I decided to go with the Teensy. I has much richer USB/HID support by default (You can start on your project right away rather than trying to mod the UNO). Teensys are also relatively cheap ranging from $18 to $24.
By comparison, UNOs are $27.18 and are out of stock. To be fair both are probably cheaper used. This is probably moot since it seems you already have one. For more info, see my question (Feasability of flashing Arduino UNO r3 with teensy firmware for HID (keyboard) emulation purposes)

There are plenty of sites out there that document how to make/build such.
Example: http://hunt.net.nz/users/darran/
or https://github.com/harlequin-tech/arduino-usb
GOOGLE: build usb keyboard 16u2

Please note that when attempting this on the Uno R3, the DFU is updating the code on the 16U2 and not the 328p.
I would suggest for novices to use the Leonardo. Where there are stock examples in the IDE for using the application directly as USB HID. Avoiding any alterations to either the boot loader or the USB to Serial co-processor chip (the 16u2). Making it much simpler.

The HEX file is simply a translated version of the AVR executable, which is in turn a translated version of AVR source code.
There are many tools available for turning (compiling) AVR source code into an AVR executable, including but not limited to the Arduino IDE, Ino, AVR-GCC, and Atmel Studio. Note that all four tools will compile the code the same way, since AVR-GCC is used under the hood by the other three.
avr-g++ -mmcu=atmega328 source.cc -o executable

Once you've compiled the code, you can use avr-objcopy to extract the appropriate sections from the executable into HEX files for programming into the flash and EEPROM.
avr-objcopy -j .text -j .data -O ihex executable executable.hex

You can then use AVRDUDE to upload the various HEX files to the target device.
avrdude -c arduino -P /dev/ttyUSB0 -b 19200 -p m328 -U flash:w:executable.hex:i

Note that the USB libraries in Arduino/Ino and AVR LibC are limited; you will need to use Atmel Studio if you want full USB capabilities.

You don't need to do something magical. Here's how you can use the Arduino IDE's affiliates.
Once you compile or upload a sketch, the .hex file is automatically created and stored in your computer's drive that has the OS installed (I've found this on Windows). You can access it by navigating to the directory containing temporary files.
Typically, the path will be something like this:
C: > Users > Admin > AppData > Local > Temp
Now you'll see (a lot of) directories with names that go like "build"... followed by a big number. One of these directories contains compiler-generated files of the code you're looking for. From this location, you can search (using Windows Explorer, for example) and identify the .hex file you're looking for by the date and time of last modification.
Once you've got your .hex file, you can upload it to your Arduino using Atmel FLIP after setting your Arduino's microcontroller to the Device Firmware Upgrade (DFU) mode. Atmel FLIP, an acronym for FLexible In-system Programmer, can be used very easily, thanks to its minimal UI.
Here's how to use FLIP:

Go to File > Load HEX File... and select the file.
Choose your microcontroller by selecting the first icon on the bar.
Choose your programming interface from the small list.

I've used this with ATXmega that supports USB but it's not the same for all.

Based on your answer, you are generating the hex files only through the use of Arduino IDE, right? Can you use Arduino IDE to, for example, write USB Human Interface Device (HID) code?

That's right, nothing other than the IDE is required. Assuming your HID is compatible with the Arduino IDE, you can. If it requires an add-on (like a Crumbuino or a Teensy, for example), it will still do the same thing. That's because it uploads the .hex file the same way. The only thing that add-on does is define custom features. You just have to find the .hex file among the temporary files. If the HID isn't compatible, you can try writing the code on Atmel Studio (only for AVR and ARM) with an appropriate compiler that can build the .hex file.


text:
2 Arduino controller boards - 1 shared input
I'm beginning with electronics and don't have all the good reflexes yet. So here is my question:
Can I do what I did here?
can i do this http://www.movod-design.com/forum_img/canIDoThis.jpg
Do I have to add diodes between the Nano +5V and the junction point?
My goal is to have one button's state read by 2 Arduino Nano.

Providing the 5V to the button should be coming from just 1 arduino. And you can also use the internal pull-up resistor from the arduino. That way you'll only need to connect one side of the button to the ground and the other side of the button to the 2 input pins of the arduino. To use the internal pull-up use pinMode(pin, INPUT_PULLUP);

Question is: why do you want two arduinos to do exactly the same? Maybe we could get rid of the second one altogether :)

You don't need to add anymore components to your schematic. But you can leave some components.
Before you're adding a button to your schematic please consider first how you want to detect your signal. A logic 1 as if a button is pressed? Or logic 0 as if a button is pressed. You can do this using pull-up and pull-down resistors. These resistors should be wired like this.

(The 100Ohm resistor in an internal resistor from the MCU)
Using the pull-down resistor means that when the button is pressed you'd get a logic 1.
Using pull-up resistors means that when the button is pressed you'd get a logic 0.
When I see your schematic it seems like you're trying to make a pushbutton with pull-down resistor. Then you should wire your arduino like this.

Another option is to use the Arduino internal pull-up resistors. That way you don't have to add the 10k resistor in your schematic. And your schematic will look like this.

To use the internal pull-up resistors from the Arduino you'll need to put this in your setup(): pinMode(pin, INPUT_PULLUP); where pin should be your pin number. Please keep in mind that when you use the internal pull-up resistor a logic 0 means the button is pressed.

thx a lot for the trouble you went through explaining at such great length! Very appreciated! :))

No problem mate. That's why we're here ;)

I have done something like this to be able to have a redundant system.
Is this what you were doing: Two computers receiving the trigger, if one computer failed you have the other running?
If that is your case, then there is a problem on this setup:

If one computer shuts down the Arduino on that computer will be powered by the second one and there will be not enough power for both.

I fixed it with a couple of diodes.
I still had some problems with false triggering from time to time, with tests on a Mac running OSX. The same tests with a Linux machine give no problem for now.
I wanted to make this really stable (next I'll try to use opto-isolators)
I'm not a Programer nor a Engineer. Please tell me if I'm saying something stupid or if there is any other easy fix.
I was using two Arduino Pro micro Chinese copies and passing the data to midi to the computers - I did not test with real Arduinos to see if it was a board problem.


text:
Trying to understand bitbanging, shiftIn(), reading EEPROM
Alright, so I have an Atmel 93C66, http://www.atmel.com/Images/doc0172Z.pdf Datasheet and I'm wanting to read whatever is in it.
I copied the following code from this thread http://forum.arduino.cc/index.php?topic=96411.0 and made some changes to it, mainly I deleted the part where it writes:
//difining pins for eeprom
int CLOCK =4;
int DATA_OUT =3;
int DATA_IN = 2;
int CHIP_SEL =5;

int low =0;     //low address

byte READ  = 0b1100;                //read instruction

void setup(){

  pinMode(CLOCK ,OUTPUT);
  pinMode(DATA_OUT ,OUTPUT);
  pinMode(DATA_IN ,INPUT);
  pinMode(CHIP_SEL ,OUTPUT);
  digitalWrite(CHIP_SEL ,LOW);
  digitalWrite(CLOCK, LOW);
  Serial.begin(9600);
}

void loop()
{

  for (int i=0;i<=511;i++)
  {
    digitalWrite(CHIP_SEL ,HIGH);
    shiftOut(DATA_OUT,CLOCK,MSBFIRST,READ); //sending READ instruction
    shiftOut(DATA_OUT,CLOCK,MSBFIRST,low);   //sending low address
    byte incoming = shiftIn(DATA_IN,CLOCK,MSBFIRST); //receiving data
    digitalWrite(CHIP_SEL ,LOW);

    Serial.print(low);
    Serial.print("/t");
    Serial.print(incoming, BIN);
    Serial.print("/t");
    Serial.print(incoming, HEX);
    Serial.println():

    low++;       //incrementing low address

  }
  while(1);
}

What I'm trying to understand is:
In the 93C66 datasheet page 5, table 6, it says that to read the contents of memory I need to send SB 1, OPCODE 10, and memory address, which I don't know exactly how to do, but I guess the chip wants a 110 (or a HIGH, HIGH, LOW signal) plus memory address (variable “low”=0). The SB and OP CODE are similar to the BYTE variable READ in the code above, but this variable has an extra 0 (1100). I tested the code with 110 and I get different incoming data. I also thought if BYTE is 8 bits then why not make the BYTE variable READ 11000000, but it changes the incoming data. So now I don't really know how exactly to send SB 1 and OP CODE 10. Need help with that.
Also, as you can see I'm printing the variable "low" and the variable "incoming" (in Binary and Hex) on one line, I thought it would be printing 1 bit per line, but it prints varying amounts of bits. Sometimes it would print 4 bits, 6 bits, or 8 bits, as in 1110, 11111111, 111100. I thought the line byte incoming = shiftIn(DATA_IN,CLOCK,MSBFIRST);
would get filled with 8 bits all the time, so when I Serial.print() it would have 8 bits, but it's not happening, why?
Also I thought the shifting in of the bits into the variable "incoming" occurs once in the for loop, or is there an inner loop in shiftIn()? I ask because I first made the for loop go for i=<4095, since there are 4096 bits in this EEPROM, but the increment of I doesn’t match the amount of bits I’m getting on each Serial.print() line.
i.e. I would get something like this:
1   10111111    BF

I thought it would be getting something like this. (I’m thinking the shiftIn() of the 1st bit at address 0 happens when i=0, then 2nd bits gets shiftIn() when i=1, and so forth)
1   1
2   1
3   0
4   1
Etc, etc

How is shiftIn() shiftinf in the bits into the BYTE variable?
Thanks and sorry if it’s so many questions.

OK I know this is a little late, but for other readers having the same problem, here's a sketch I wrote to read a 93c46 when I had to dump the EEPROM from a car radio. I've deliberately not included the EWEN instruction anywhere as the last thing I wanted to do was accidentally write to the EEPROM.
The key is the modified shiftOut routine which adds a parameter specifying how many bits you want to shift out.
To adapt sketch for other 93c packages, change the number of 16bit words at start of loop{} and number of address bits in 2nd call to myshiftOut.
If your package has an ORG pin, tie it to Vcc.
Hope this helps someone...
/*
Arduino Uno sketch to dump a 93c46 EEPROM in 16 bit mode.  Metalbanana 12/9/16, with thanks to raint.
Easily modified for other 93c series parts. Note many 93c46 from autos are 'rotated' pinout,
i.e. those with a T following part no. e.g. 'TEM8':

1=NC    8=ORG
2=Vcc   7=GND
3=CS    6=DO
4=SK    5=DI

so check pcb for Vcc and GND locations with a meter first! An Arduino ProtoShield is ideal to mount IC
as it has a SOIC pad (Note: you can't use the mini breadboard at same time as it covers one set of headers).
Standard shiftOut is not suitable as it sends 8 bits, our addresses are 6 bits,
instructions are 3 bits so sketch uses a modified shiftOut called myshiftOut.
*/

// define pins for eeprom
const int CHIP_SEL = 8;  // to CS
const int CLOCK = 9;     // to SK
const int DATA_IN = 10;  // to DO
const int DATA_OUT = 11; // to DI

const byte READ  = B110;                //read instruction

bool debug = 0;

void myshiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, byte val, uint8_t bits)
{
  for (int i = 0; i < bits; i++)  {
    if (bitOrder == LSBFIRST) {
      digitalWrite(dataPin, !!(val & (1 << i)));
      if (debug)Serial.print(!!(val & (1 << i)));
    }
    else
    {
      digitalWrite(dataPin, !!(val & (1 << (bits - 1 - i))));
      if (debug)Serial.print(!!(val & (1 << (bits - 1 - i))));
    }
    digitalWrite(clockPin, HIGH);
    digitalWrite(clockPin, LOW);
  }
}

void setup() {
  pinMode(CHIP_SEL, OUTPUT);
  pinMode(CLOCK, OUTPUT);
  pinMode(DATA_OUT, OUTPUT);
  pinMode(DATA_IN, INPUT_PULLUP);

  Serial.begin(9600);
  Serial.println("\n\n");
}

void loop()
{
  for (int addr = 0; addr < 64; addr++) // 64 words for 93c46
  {
    // print address at start of each line
    if (addr % 8 == 0) {
      Serial.println();
      if (addr < 8) Serial.print("0");
      Serial.print(addr * 2, HEX);
      Serial.print(": ");
    }

    digitalWrite(CHIP_SEL, HIGH);
    myshiftOut(DATA_OUT, CLOCK, MSBFIRST, READ, 3); //send READ instruction
    myshiftOut(DATA_OUT, CLOCK, MSBFIRST, addr, 6); //send address, 6 bits for 93c46

    digitalWrite(CLOCK, LOW); // recommended in language reference
    byte incomingH = shiftIn(DATA_IN, CLOCK, MSBFIRST); //receive high byte
    byte incomingL = shiftIn(DATA_IN, CLOCK, MSBFIRST); //receive low byte

    // reverse byte order & print
    if (incomingL < 16) Serial.print("0");
    Serial.print(incomingL, HEX);
    Serial.print(" ");
    if (incomingH < 16) Serial.print("0");
    Serial.print(incomingH, HEX);
    Serial.print(" ");

    digitalWrite(CHIP_SEL, LOW);
  }

  while (1);
}


text:
Photoresistor and another switch
I am using the circuit diagram below to turn ON/OFF the lights using Photo-resistor.
How can I use the Arduino to bypass the Photoresistor effect?
Let say I want to turn ON the lights even though Photoresistor doesn't want to.
Take note the 12V source is required by the LED. Knowing that Arduino must work with max 5V.

You could replace the circuit with these:

Use one Arduino analog input to measure the light.
Use a Digital Out (Preferable PWM) to control the LED.

Then you can apply whatever logic you want.

simulate this circuit – Schematic created using CircuitLab

Among the other answers, this is the best, especially because:

The arduino can read the light intensity. 2) You can choose of having the LED either on or either off, or its intensity to be inversely proportional to the amount of light 3) you can easily add hysteresis by software 4) you can choose the threshold level, without having to change the pull-up resistor.

One thing though: i would put R1 connected to the arduino GPIO and not to the gate, so that there won't be any divider. M1 must also be a 5V logic level MOSFET. Or you can use a BJT.

@next-hack R1 and R2 is NOT a voltage divider, its a common practice to pull down a MOSFET to ensure that it is in an normal OFF state and the value for R1 would be in 10K to 100k area. R2 is to protect Arduino from a faulty MOSFET that shortens the output and could be in 1K area.

I didn't write that R1 and R2's purpose is a divider, but the side effect is. To avoid this, you need to use R1 values at least an order of magnitude larger than R2, as you wrote. If you put R1 on the left (keeping R2), this constraint is removed. In this way, when the GPIO is uninitialized (i.e. during reset, in most  - but not all - MCUs the GPIO ia at high impedance), M1 is kept in the off state by the series R1+R2. However, some MCUs might have some pins which even during reset have a -relatively- strong pull up, so you might want R1 low enough to force off state on M1.

@next-hack Now you are splitting hair strands! Over and out.

There are several ways to add Arduino control; the question doesn't provide quite enough information to say which is best.
One of the simplest methods is to use a diode to clamp the transistor's base voltage to at most 5 V, as shown in the following diagram.  The voltage at the IO pin cannot exceed 5 V plus one diode drop.
With this circuit, setting the IO pin to be an input leaves the LED under photoresistor control.  Setting the IO pin as a low output turns off Q1, and setting it as a high output turns on Q1.   Note, R3 should limit the current drawn from the IO pin to at most about 25 mA, so 150 to 200 Ω may be suitable.

Yay! A fellow gschem user! ;)

Be careful with the 12V, the Arduino can not handle 12V at its pins.
The input can be the photoresistor with a resistor to 5V (not to 12V). Use a analog input to measure the amount of light.
The output can be with a resistor to the base of the transistor.
This is an example: PighiXXX transistor
Any unused digital output can be used.
Why do you need 12V for the led ? Is it a special led ?