text:
Common Wire sizes for connecting peripherals to arduino
Please don't judge me for asking this question i have never touch arduino before but We plan to use it in our thesis we are doing a budget plan and it must include wires. can anyone tell me the common wire sizes used? This is to estimate the prices.

Used for what? Different purposes need different sizes.

Wire size (i.e. diameter) depends on the amount of current traveling through it. For most arduino stuff, wire size isn't really that important. You can just reuse wires from unused cables. Ethernet cables are a great source of wires. Decent diameter, and different colors (very handy).

Depends what you’re doing.
For low power (< 12v, 500mA) peripherals and digital signals:
If you’re going to use breadboard (and you really should start with breadboard) you’ll need solid core hook up wire. You can find pre-cut, pre-stripped sets with a variety of lengths and colours if you’re looking for neatness and simplicity.
(An example can be found at: http://www.maplin.co.uk/p/jump-wire-kit-fs65v)
Usually it’s 22AWG wire, so you could get a reel and cut it yourself if you’re going to need a lot or are going to solder it in place.
After you’re done breadboarding and want to make something more permanent you should look at rainbow cable. You can tear it to get anything from 2 to 32 way cables, and it’s almost impossible to get the wrong way around. You can solder it directly to a PCB or crimp connectors onto the ends for more flexibility.
(You can find this stuff everywhere, but Sparkfun is always there if you can’t: https://www.sparkfun.com/products/10649)
For higher power (> 12v, 1A):
Keep it away from the Arduino! Use switching transistors, relays, or MOSFETs and use cabling that meets, or preferably exceeds, the power that you’re going to put through it.
I don’t know where you’re going to buy this, but in the UK I use Mouser, Farnell, and RS for most of my electronics supplies. Never buy cabling off Ebay, a lot of it is counterfeit and won’t meet the claimed spec.
Hope this helps.

We have Mouser outlets here in the US as well. Also Digikey, Jameco, and quite a few others.

Thanks a lot.. you really helped.. It's good to read an answer that makes sense..

I wonder in which way eBay cable can be counterfeit? Not the claimed gauge? Not tinned or not copper? Insulation not heat tolerant?

@thomasrutter All of the above. I've seen "copper" core cabling clearly some bastard mix of metals to make it cheaper, 16 gauge wire sold as 12, and "silicone" insulation that flaked right off the reel (a fire risk for what we were going to use it for). Don't even ask about "un"twisted pair, "un"shielded, and coax that isn't. I'd always pay ~30% more and get the genuine stuff from a repitable supplier and save yourself a world of rage.


text:
How to wire QRB1114 IR sensor to an Arduino Uno
What's the best way to wire a QRB1114 IR sensor to an Arduino Uno? I'm attempting to use it as a white-line-on-black-background line detector. Google shows many different ways wire it to an Arduino, but I'm using this one because of its simplicity.
However, when I tested the circuit using the AnalogInput example code, I'm not getting the expected behavior. It registers a reading of 0 for both white and black backgrounds (I'm using white and black electrical tape as test surfaces), and occasionally registers between 5-10 if there's nothing in front of it at all.
What is the most likely problem? Is this circuit an improper way of wiring the sensor? Is my sensor defective? Is the code not reading it properly?
This is my test code:
#define BUTTON_PIN 2
#define LED_PIN 13

const int IR_SENSOR_PIN = A0;
int sensorValue = 0;

void setup() {
    Serial.begin(9600);
    pinMode(LED_PIN, OUTPUT);
}

void loop() {
    sensorValue = analogRead(IR_SENSOR_PIN);
    Serial.println(sensorValue);
    delay(1000);
}

It was a dumb programming/wiring problem on my end. As I discovered from this description, the signal pin needs a pullup resistor. Since my circuit doesn't have that, I need to enable the pullup resistor on A0, which I wasn't doing.
After modifying my code to do that, the sensor works as expected.

Good find. Depending on the range (white vs black surface) you get from analogRead you might want to use a different value (external) resistor.

source: Stack Exchange

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

sort: votes


text:
ATmega168a Breadboard - can't load via Arduino IDE
I have ATmega168a on a breadboard. I am programming it via the Arduino IDE and a FT232RL USB adapter. When I select my board for 168 and upload, I get the following error:
stk500_getsync(): not in sync: resp=0x00

Normally this error means that either:

My wiring is not correct
I choose the wrong board

So to double check my wiring, I replace the 168 with a 328p. I am able to program the 328, so I think its the board selection.
I have tried Ardiono Diecimila or Duemilanove w/ ATmega168 and I also have a custom board entry:
atmega168bb.name=ATmega168 breadboard (16 MHz internal clock)
atmega168bb.upload.protocol=stk500
atmega168bb.upload.maximum_size=14336
atmega168bb.upload.speed=57600

atmega168bb.bootloader.low_fuses=0x62
atmega168bb.bootloader.high_fuses=0xDF
atmega168bb.bootloader.extended_fuses=0xF9
atmega168bb.bootloader.path=arduino:atmega
atmega168bb.bootloader.file=ATmegaBOOT_168_atmega328_pro_16MHz.hex
atmega168bb.bootloader.unlock_bits=0x3F
atmega168bb.bootloader.lock_bits=0x0F

atmega168bb.build.mcu=atmega168
atmega168bb.build.f_cpu=16000000L
atmega168bb.build.core=arduino:arduino
atmega168bb.build.variant=arduino:standard

Also, I am able to program the 168 via my AVR Programmer/Debugger. If you are wondering why I should just use the AVR Dragon, there reason is that I a sometimes don't want to remove the chip from the bread board while developing and programming.
Any suggestions I can try?

Did you program an Arduino bootloader into the chip? Also, jumper wires.

Yes - with ATmegaBOOT_168.hex - And by jumper wires, what do you mean?

The internal oscillator is 8mHz, not 16mHz. That means serial runs at half the speed. So you could try atmega168bb.upload.speed=28800

@Gerben Thanks but that didnt work either. I'll continue to work on it. I can use the SPI/ISP programmer, but this is killing me why it won't work!

Have you burned a bootloader?
The standard Arduino IDE upload requires that you have a bootloader on the chip.
You can burn a bootloader with the Arduino IDE and your AVR dragon

Try adding a 1k resistor on the TxD and RxD pins to your chip. And a 100nF capacitor like the schematic below. And a 10k Pull-up resistor to the reset pin.
Target processor                                 USB to Serial converter
(Atmega 168)
GND   ------------------------------------------ GND

5V    <----------------------------------------- 5V
RX    <--- 1K ---------------------------------- TX
TX    ---- 1K ---------------------------------> RX
RESET <----||----------------------------------- DTR_PIN
  |       100nF
 10K
  |
 5V

This will help stabalizing the signals.

This will not "stabalize" things.  What you are showing is a mix of ideas - some resistors for pin sharing or lazy level conversion, and an auto reset circuit.  The auto reset might be useful, but unless the ATmega and USB serial solution are running at different voltages, the resistors will not help.

I see. If I wasn't wrong I had some like the same problem as the person who asked this question and fixed it using my answer. Found that on the arduino website back then. Can't really remember it clearly though....

There is another possibility, which I have had in the past.
My AVR was brand new, and it was set to use the internal resonator, at 1/8th speed, for a total of 1mhz. This was too slow to program using the default settings.
I had an USBASP, and it very conveniently had "SLOW SCK" jumper option, to slow down the programming. This was enough to program it, and if I'd wanted to use an external crystal clock (which I didn't, and 1mhz was fast enough for the specific project), I could have changed the fuses Check out http://www.engbedded.com/fusecalc/ to calculate new fuse settings. Be careful, I managed to set one chip to the wrong fuses, and am no longer able to change it.
P.S. - I used AVRDUDE to program the fuses. You should be able to read the current values, before you start - again, at slow speed. AVRDUDE has the '-B' option to slow down the programming, if you do not have the "SLOW SCK" jumper option, option -B10 should be plenty (default = -B1 I think).
When checking what the current fuse settings are, I think the main ones that slow down the clock are: CKSEL and SUT (the top dropdown list on the calculator website), and CKDIV8 - divide clock by 8; the second tickbox on the list. The defaults for these for AtMega 168 should be: Internal RC Oscillator: 8mhz, and the "Divide clock by 8" option selected.

This is indeed a possibility in other settings, but keep in mind that the question here concerns programming via serial communication with a bootloader, not ISP, and that the poster has reported that ISP is working.

. If you are wondering why I should just use the AVR Dragon, there reason is that I a sometimes don't want to remove the chip from the bread board while developing and programming.

Your dragon is an ISP so you don't have to unplug and replug it for programming.
I would check if your ftdi board an indeed function as a stk500.
Another alternative is to burn the bootloader and go down the regular Arduino route.

you should be selecting the Arduino NANO board as the original Arduino Nano board is equipped with the FT232RL, rest all have either atmega chip for usb to ttl conversion or CP2302 chip. So select Arduino Nano and try.

Which serial converter is in use does not matter.  It is appropriate to select a proper board configuration, but not for that reason.  In fact historically and even today for the boards concerned here, the boards.txt doesn't even contain any information about the USB serial solution in use.  A few entries such as for the Uno do now contain USB/VID information but that is probably only to help the user find the right serial port - it wouldn't change behavior in how avrdude talks on that port.

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


text:
Flashing a ATmega328 that came from an Arduino to not use an external oscillator
I have a ATmega328p chip from a kit that was supposed to be an Arduino compatible thing. I decided to go beyond Arduino and try to program the chip directly. I setup an UNO as an Arduino ISP, more or less like the image here, but added some LEDs to pins 8, 9 and 10 for feedback.

This image has this caption.

Because no external clock source is connected, the ATmega must be configured to use its internal clock.

I think this chip was flashed with whatever tells it to use an external oscillator. And I do not have an external oscillator.
So how can I tell the chip to again use an internal oscillator when using an UNO as my programmer?
» avrdude -p m328p -c avrisp -b 19200 -P /dev/cu.usbmodem1d11121

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.05s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

I assume a device id of zero means the chip is not responding with data? because it's core is not cycling?
Do I need an oscillator installed just so I can wake it it up and tell it to not use an oscillator?

If the chip was blank, it would be running at 1mHz. You'd need to lower the programming speed (avrdude -B10 ...).

@Gerben Mega, not milli ;)

Do I need an oscillator installed just so I can wake it it up and tell it to not use an oscillator?

Yes, yes you do.
Pick up a 8-16MHz crystal (not an oscillator) and two 15pF capacitors and use very, very short wires to connect them to the chip as shown in the "System Clock and Clock Options" section of the '328P datasheet. You will then be able to reprogram the fuses using AVRDUDE.

Even though an answer has been accepted, I just want to add for future viewers that you can google for arduino breadboard internal oscillator and get the text to copy into the boards.txt file.  That will allow you to use the Arduino IDE to burn the fuses.  You will be able to find versions to run at both 8mhz and 1mhz.
Also, if you have an extra Uno laying around, you could always pop the chip in there and reset the fuses, then take it out and use it on a breadboard.

But note that even though you will be able to do it via the Arduino IDE, you cannot set fuses through the serial connection; you must use ISP or HVPP in order to set fuses.


text:
ICP Accelometer Arduino
I need to connect piezoelectric accelerometer to Arduino. Precisely, it's this one: http://www.pcb.com/Products.aspx?m=352C34
Specs show that it generates 100 mV/g, but when I connected it between ground and analog input with 1M pulldown resistor, analog input stays at 0.
Arduino analog input resolution and accuracy is absolutely fine for now.
Could someone point me to right direction in connecting this kind of sensor to Arduino?

How do you provide power to the device?

Can you show your exact circuit?

That device appears to both require a non-trivial interface circuit, and to be intended for measuring vibration, not steady accelerations such as gravity.  It has a minimum frequency of one cycle every 2-3 seconds.  Also note the series capacitor in their sample setup.


text:
Auto detecting Baud Rate of Arduino
I'm trying to detect baud rate of Arduino Mega2560 by using C#. My code is below:
SerialPort SP=new SerialPort();
SP.BaudRate = 115200;

BaudRate is specified as a constant like this, but I would like to automatically detect it.
For instance, if Arduino code includes Serial.begin(xxxx), program should declare SP.BaudRate = xxxx.
How can I do it?

I'm not a C# programmer but this StackOverflow answer might be what you're looking for.

Note that to do this, there has to be a way to get an expected response from the device.

True, but you'll probably want some sort of basic handshaking anyway.


text:
'readPulsioximeter' was not declared in this scope
I am new to Arduino. I am trying to use Pulsioximeter sensor with e-health Platform (http://www.cooking-hacks.com/documentation/tutorials/ehealth-biometric-sensor-platform-arduino-raspberry-pi-medical) on Arduino Uno. Line number 13 is working fine in the example code given in the library and works just fine. But when I try to upload my custom code (setup function definition is given below), I get an error stating 'readPulsioximeter' not defined in this scope. The error doesn't seem obvious to me. Please guide.
Here is the custom code upto setup() function:
#include < eHealth.h >
#include < PinChangeInt.h >
bool configuration = false;
//bool in_it=true;
byte val; // variable to receive data from the serial port
int ledpin = 13; // LED connected to pin 48 (on-board LED)
int A=1;
void setup() {
           pinMode(ledpin, OUTPUT);
           Serial.begin(115200);
           eHealth.initPulsioximeter();
           //Attach the interruptions for using the pulsioximeter.
           PCintPort::attachInterrupt(6, readPulsioximeter, RISING);
           delay(500);
}

 EDIT1:
readPulsioximeter is declared in eHealth.h library which has been included in program. The function has been defined as below in eHealth.cpp file:
    //!******************************************************************************
    //!     Name:   readPulsioximeter()                                             *
    //!     Description: It reads a value from pulsioximeter sensor.                *
    //!     Param : void                                                            *
    //!     Returns: void                                                           *
    //!     Example: readPulsioximeter();                                           *
    //!******************************************************************************
    void eHealthClass::readPulsioximeter(void)
    {
        uint8_t digito[] = {0,0,0,0,0,0};
        uint8_t A = 0;
        uint8_t B = 0;
        uint8_t C = 0;
        uint8_t D = 0;
        uint8_t E = 0;
        uint8_t F = 0;
        uint8_t G = 0;
        for (int i = 0; i<6 ; i++) { // read all the led's of the module
            A = !digitalRead(13);
            B = !digitalRead(12);
            C = !digitalRead(11);
            D = !digitalRead(10);
            E = !digitalRead(9);
            F = !digitalRead(8);
            G = !digitalRead(7);
            digito[i] = segToNumber(A, B, C ,D ,E, F,G);
            delayMicroseconds(2800); //2800 microseconds
        }
            SPO2 = 10 * digito[5] + digito[4];
            BPM  = 100 * digito[2] + 10 * digito[1] + digito[0];
    }

The problem is that you have no function called "readPulsioximeter" in your code. Either define it, pick a different function, or remove that line of code.

readPulsioximeter is declared in eHealth.h library which has been included in program. Please see EDIT1 in the the question.

:) Thanks for your help. I re-defined the function in the program and it worked.

It looks like your missed naming the eHealth object, and that that statement should read:
PCintPort::attachInterrupt(6, eHealth.readPulsioximeter, RISING);
as you did with the initPulsioximeter call. (In otherwords, "which pulsioximeter?").

When I try specifying eHealth.readPulsioximeter, it is shown as unresolved overloaded function type. Problem is that the same line is working in another program but gives error in this program.

:) Thanks for your help. I re-defined the function in the program and it worked.


text:
Arduino Yun - Sensor Data logging to MYSQL on External Server
I want to log data from Sensors (Say Temperature, moisture or humidity) to a MYSQL database (provided by a online hosting company). Is it possible to establish communication between Arduino Yun and that database and log the data to it

Yes, you can do that using python as well as other languages, or you can use Temboo: there's an example bundled with the Arduino IDE, it's called "SendDataToMySQL"


text:
avrdude: usbdev_open(): did not find any USB device "usb"
I was programing the arduino and things were going great.
Then I plugged in another chip, and went to burn a boot loader.
(New chips) now, I get:
avrdude: usbdev_open(): did not find any USB device "usb"

when I try to upload code to old chips, I get:
avrdude: usbdev_open(): did not find any USB device "usb"

ten times.
I have tried reseting, and it doesnt do anything.
when I plug the device in,
dmesg shows that the device responds to my PC
[526199.130716] usb 3-1: new full-speed USB device number 7 using xhci_hcd
[526199.149422] usb 3-1: New USB device found, idVendor=2341, idProduct=0043
[526199.149427] usb 3-1: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[526199.149430] usb 3-1: Manufacturer: Arduino (www.arduino.cc)
[526199.149433] usb 3-1: SerialNumber: 649343332353518022F0
[526199.149579] usb 3-1: ep 0x82 - rounding interval to 1024 microframes, ep desc says 2040 microframes
[526199.149766] cdc_acm 3-1:1.0: ttyACM0: USB ACM device

IDE settings:
board: Audruino Uno
serial posrt /dev/ttyACM0
Programer: AVRISP mkII
I also tried AVR ISP
in the command line, I tried:
   avr-gcc -DF_CPU=16000000UL -mmcu=atmega328 -o Balls.out Balls.c
   avr-objcopy -O ihex -R .eeprom Balls.out  Balls.hex
   sudo avrdude -V -F -c stk500v1 -p m328 -b 19200 -P /dev/ttyACM0 -U flash:w:Balls.hex

each time, I get:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

How can I troubleshoot the Arduino Uno?
Is this thing broken?

You (or your IDE) are using the wrong command line arguments for an Arduino UNO - although connected via USB, as far as avrdude is concerned it is a serial device, not a USB one.  In the case of your linux box, the first one connected appears to be /dev/ttACM0

it is on /dev/ttyACM0

Yes, you need to make use of that information.  If you are using the IDE, try the various selection menus.  If you are using the command line, edit what you have now into your question and you'll get suggested corrections.

Ive tried variations. Im doing the exact same things that have worked previously. How does someone troubleshoot an arduino uno?

First, add yourself to the dialout group or whatever owns /dev/ttyACM0 and re-login so you can get the sudo out of there.  Next, which error message are you currently getting?  Are you still getting the USB one?  If you are just getting the not responding complain, that points more towards a bad baud rate, an unreset board, missing bootloader, or damage.

the usb error is when i try to burn a bootloader.
the programmer not responding is when I try to upload code

Sounds like you should describe (connection and command) your attempt to burn a bootloader.

Question has been abandoned without the followup necessary to resolve, voting to close.

I agree with @Chris. Because this question is needlessly complex. I'll re-ask the question with my answer.

Generated from IDE
Because this is a generic error, I'll answer it. I was getting this on STDERR when using the IDE:

avrdude: usbdev_open(): did not find any USB device "usb"

This is because in the IDE I was using

Sketch → Upload Using Programmer [Ctrl + Shift + U]

However, I should have been using

Sketch → Upload [Ctrl + U]

Ultimately the comments clarified that this error was produced when trying to burn a bootloader rather than when trying to load a sketch.  Burning a bootloader can only be accomplished by means of a programmer.  It is unclear what programmer was available to the original poster - specifically if it was one connected via a (virtual) serial port or one connected as a native USB device.

@ChrisStratton new question with answer

Evan, you deserve a place in heaven for this answer!


text:
Asynchronous control framework
Can anyone recommend an Arduino-based asynchronous scheduling library for controlling a small mobile robot?
I'm writing the control code for a small 2-wheeled Arduino-Uno based robot. It has a few bumper sensors, IR sensors, and ultrasonic sensors. I've written an initial pass from scratch, using loop() to read sensors and set motor values appropriately and then wait for the motor to have effect, but I'm finding this cluggy. Some of the sensors, like the ultrasonic range finders, require a small delay to operate, and the motors require a delay to have an effect. Blocking loop() is the simplest way to achieve this, but it wastes cycles, and can be difficult to time each action properly without throwing off other behaviors. Writing an asynchronous scheduler would be more efficient, but a lot more complicated, and I expect I would be reinventing the wheel.
I found this list, of existing scheduling libraries, but I'm not sure which, if any, would be appropriate.

You may also want to take a look at cosa library on github.

@jfpoilpret, Interesting. I'm not sure I want to throw out the default Arduino library just to use some scheduling componenets. And it's a shame Cosa's documentation is so bad. Why do so many developers think a class index with few comments and no examples is all they need for docs? Looking through that, it's not clear what I should use. It has a Timer, Alarm and Periodic class, as well as a few other classes that may be scheduling related as well.

you're a bit unfair about documentation, it is not bad at all (compared to the standard arduino lib at least). Regarding examples, there are more than 100 of them and they are even a very good way to learn Cosa.

@jfpoilpret, I would agree that standard Arduino docs aren't great either, but the examples are better broken down by features set. I did see Cosa's examples directory, but other than the CosaAlarm example, I don't see anything else that uses the scheduling classes.

Hello, I'm currently testing leOS / leOS2 (see https://github.com/leomil72/ ) which seems to be a very nice scheduler lib for Arduino

I recommend writing your own in C++.  Arduino works well with C++ as it is written in C.  You can focus on getting the asynchronous behavior to do what you need instead of writing drivers.  I don't think it will take any longer to learn enough C++ to make this work than it will to learn to use, and possibly fix, a library. Your C++ knowledge will be much more generally useful than knowing a specific library.
Igor points out the advantages of going to a real time operating system.  I agree and think that, if you want to work on robots long term, you should go with an RTOS and get away from Arduino. Working with C++ and Arduino is one way to get started.

I would recommend ChibiOS: albeit it just got support for Arduino and it lacks a few drivers (I'm writing one for INTx and PCINT), it's got a fundamentally healthy design, a community around it and the author himself is very responsive.
You might have to write or port the drivers for external shields, however the upside is to get rid of the cruft that plagues most of the Arduino libraries.
You can even choose between 2 RTOS:

ChibiOS RT, a full fledged RTOS.
ChibiOS NIL, a minimalistic OS, actually almost a scheduler, which leaves more space and execution time for your own code. -
But if you check the amount of FLASH taken up by a typical binary built with the default Arduino libraries, you will see that it pulls in a large amount of typically unused stuff, so you could trade that for the use of the full fledged RT.

Disclaimer: I'm just a very happy user of the OS, I do not have any other involvement with it, especially the commercial part.


text:
Need help to send serial data from arduino to XBee and to another XBee wirelessly?
I try to send serial data RPM to XBee series1 and then from XBee to another XBee wirelessly in API with Escapes Mode. I think I have to send the data Frame.But not very sure.
Any help?
Following is the code to read RPM and send to XBee?
#include <XBee.h>
#include <SoftwareSerial.h>
/* Serial communication with Xbee.
On Arduino pin 9 is Rx connect to Xbee Tx,
pin 8 is Txconnect to Xbee Rx*/
SoftwareSerial xbeeSerial(9, 8); // RX, TX

XBee xbee = XBee();

int pin = 7;  //7
float rpm;
float duration;
float y;

unsigned long val,time;
float rps;
float read_rpm;

uint8_t start_data[] = { 0x7E, 0x00, 0x50, 0x01, 0x01, 0xff, 0xff,0x00, 0x05, 0x00,0x01,0x03, 0x84, 0x00 };

void setup()
{
  Serial.begin(9600);
  pinMode(pin, INPUT);
  Serial.println("I am ready to send some RPM!");
  xbeeSerial.begin(9600);
  time = millis();
}

void loop()
{

void loop()// run over and over
{
 val =  pulseIn(pin, LOW,70000000);

 duration=(float)val/1000000.00;
 rps= 1.00/duration;
rpm=60.00*rps;

/* Sending float to Xbee
Float is 4 byte size*/
serialFloatPrint(rpm);

int floatToInt = (int)rpm;

/* To send INT to XBEE
Int is 2 byte size*/
xbeeSerial.write(highByte(floatToInt));
xbeeSerial.write(lowByte(floatToInt));

  Serial.write(0x03);

  delay(2000);
}

void serialFloatPrint(float f) {
  byte * b = (byte *) &f;

  //xbeeSerial.print("f:");
  xbeeSerial.print(b[0]);
  xbeeSerial.print(b[1]);
  xbeeSerial.print(b[2]);
  xbeeSerial.print(b[3]);
  /* DEBUG */
  Serial.println();
  Serial.print(b[0],BIN);
  Serial.print(b[1], BIN);
  Serial.print(b[2], BIN);
  Serial.println(b[3], BIN);
  //*/
}
}

As @TMa showed, download this library and first test the communication without any RPM calculation. When you will be sure you get good messages on another arduino, then add rpm and etc... In Xbee-Arduino library there are examples

Please use the code tag.

@werner, where is the code tag?

couldn't find the example what I want. I tried the following. Though can't recevive any serial data.

I got stucked with this. Any help?

Dear zalt, it is hard to read code in comments. Please edit your question and add the code there

Sorry. I did it.

Your code is unreadable.  Please learn how to use the code tag. http://meta.stackexchange.com/questions/22186/how-do-i-format-my-code-blocks

I did. Is there any solution?

Any hint? What is the solution?

You are using it as in non-API mode when data are passed to Xbee wireless transparently. To use Xbee in API mode use e.g. Xbee-Arduino library.


text:
How to convert byte array to float
How can I convert a byte array to float?
Code:
void send_data() {
    CCPACKET data;
    data.length=2;

    float lon=26.533255;
    float lat=27.533463;

    data.data[0]=lon;
    data.data[1]=lat;

    if(cc1101.sendData(data)){
    Serial.println(data.data[0]);
    Serial.println(data.data[1]);

    Serial.println(" sent ok ");
    return true;
    }else{
    Serial.println("sent failed ");
    return false;
    }

 }

The problem is when I print those two variables it just prints lon 26.00 and lat 27.00 but not lon 26.533255 lat 27.533463 as I expected.
Here is the header file for CCPACKET I use:
#ifndef _CCPACKET_H
#define _CCPACKET_H

#include "Arduino.h"

/**
 * Buffer and data lengths
 */
#define CC1101_BUFFER_LEN        64
#define CC1101_DATA_LEN          CC1101_BUFFER_LEN - 3

/**
 * Class: CCPACKET
 *
 * Description:
 * CC1101 data packet class
 */
class CCPACKET
{
  public:
    /**
     * Data length
     */
    byte length;

    /**
     * Data buffer
     */
    byte data[CC1101_DATA_LEN];

    /**
     * CRC OK flag
     */
    boolean crc_ok;

    /**
     * Received Strength Signal Indication
     */
    byte rssi;

    /**
     * Link Quality Index
     */
    byte lqi;
};

#endif

I was trying to fix it by this part of code, but without success:
float lon=26.533543;

*((float *)data.data[0]) = lon;

Can someone help me to convert the byte array to float?

Do you know how many bytes a float uses?

Hmm unfortunately no.

Your first task is to discover the answer.

You can choose to treat the byte array as a float array by typecasting. Your attempt isn't far from a solution:
((float *)data.data)[0] = lon; // uses data.data[0] ... data.data[3]
((float *)data.data)[1] = lat; // uses data.data[4] ... data.data[7]

When printing you should also treat the data array as float array:
Serial.println(((float *)data.data)[0]);

It looks like you are sending the data over some interface. Then of course you need to typecast the binary data back into a  float at the receiving end (if you want to do something useful with it) - similar to what is done above when it is passed to Serial.println.

Hi thank you for helping me, it was useful :) Now it is possible  to send data with decimal. I was trying to receive data like this:                                                      loat lon=((float *)packet.data)[0];
float lat=((float *)packet.data)[1];
  Serial.println(((float *)packet.data)[0],4);
  Serial.println(((float *)packet.data)[1],4);              But without success. What could the problem be? Again I want to than you :)

The output I got is 0.0000 and 0.0000

Did you update the packet size (data.length)? Each float eats 4 bytes, so it has to be 8 now.

Hi, I'm not able to fix it by my self. How/where can I update the the packet size?

Try data.length=8 in your send_data routine.

Aha you are right :) Thank you for helping me :)

/**
  Data buffer/
  byte data[CC1101_DATA_LEN];

That line of code declares an array of datatype byte. I suggest you review variable declaration for Arduino.
A byte will store an 8-bit unsigned number with a range of 0 to 255, no decimal points. I also suggest you review truncation to understand how computer systems handle mathematic calculations that produce decimal results when the result is being stored in a variable type that doesn't store decimals.
A float stores a 32-bit value with decimal point.
The quick answer to your problem is to change the above quoted code from byte to float.

Except now the CC1101 code will need to be changed to accept floats and transmit bytes. So, nothing saved.

True, it would have to be followed through with on all related functions. It could get messy. In any case, the issue is that CC library is set up for bytes rather than floats.


text:
What does the datasheet information for a switch mean?
I'm clueless when it comes to the information on datasheets for switches. When I see a datasheet for LEDs or servos, I'm used to seeing a fairly straightforward call out for the required volts and amps.
A project I'm working on now requires turning on an LED using a float switch like this one:
Water Level Switch
The max switching voltage and current values, and minimum voltage info is really throwing me. The minimum voltage, for instance, is 250v DC! Does a $5 switch really require 250 volts? I haven't been able to find many schematics where they are just using a switch like this without a pump or other hardware, but I seem to remember seeing someone run a switch like this with 5v pin. And I'm totally unsure what the current would be/if I need a resistor, etc.

I think that "minimum voltage" must be the "minimum damage voltage", i.e. the switch is guaranteed against damage until 250 Vdc.

It's just a reed-switch, so it should work just fine with any voltage (below 100v). I think the 250V is the "minimal breakdown voltage". I see that term in some reed switch datasheets.

Ah, interesting. I haven't seen that called out in any Arduino materials I've read so far, but I'm pretty new to this. If one/both of you post as an answer, I'll accept.

Thinking about this again, datasheets for these kind of switches don't seem to indicate what the minimum voltage and current are. How might I go about figuring that out?

A reed switch like this will not require any minimum voltage. It should work quite happily down to millivolt levels. If you want to switch on an LED from a 5V supply that is switched by the reed switch you will need a resistor that limits the current to no more than
20mA. The forward voltage drop over a red LED is around 2V so your resistor will drop 3V which means it needs to be at least about 150 ohms.

It says "maximum breakdown voltage: 250 V DC". That's maximum, not minimum. Above 250 V DC the arc which is created by an opening contact isn't guaranteed to extinguish. It's defined for DC voltage because then the arc remains; for AC the arc will extinguish automatically when the current crosses zero.

Looks like they changed the data in the listing or the datasheet since I originally posted this, and you're right, now it says maximum breakdown. Either way, I hadn't see anything about arcs and your info is useful and I appreciate the comment.


text:
Can I simply unplug the Arduino usb if serial communication is active?
So, after the sketch is uploaded, and I want to turn the Arduino off while it is running a sketch, all I have to do is unplug it.
Should be safe as long as nothing is uploading.
But I wonder, if I use serial communication between the Arduino and my Computer in a sketch, does it harm either if I simply unplug it?

No, it won't harm your PC or arduino. Microcontrollers are actually pretty good at abruptly stopping and starting. The PC is just reading the stuff you send to it and at some point he won't receiver stuff anymore, but he won't care.

if the sketch is uploaded, it wont hurt it to unplug. Just give it another source of power and it will run its sketch.

So, even if there is serial communication, it won't harm them? Because, if I unplug my external hard drive during communication with my Computer, it can be very harmful. I don't want to fry the little one...

If you unplug the Arduino when it is running it will just shut off and no new data will be recieved or sent, the connection would just stop. So un plugging it wont do anything negative to the Arduino it's self but if the Arduino is using memory like an eeprom or flash, it may store corrupt data. Thats why it isn't advised that you disconnect things like hard drives when they are running. Although in reality just disconnecting the hard drive from usb wont damage anything because of safety features that are built in. Removing a built in hard drive while it was running would likely corrupt data.

You can unplug it, it does not harm.
If your arduino does not need power, eg. for writing EEPROM or FLASH, then no danger there.
(in case it was writing EEPROM/FLASH it could write it faulty but usually even that is not a problem either)

Yes, you can unplug it directly whether if serial communication is active or not if you dont need power supply anu more using usb cable


text:
Breakout vs Shield
I would like to extend my arduino uno with WIFI and I am checking different options.
These are:
Adafruit-CC3000-Breakout-with-Onboard-Ceramic-Antenna
Arduino WiFi Shield (integrierte Antenne)
Viewing the price, obviously I understand that the shield will have more functions, I think also it is more "friendly" for programming and the breakout requires more low level code(I am not afraid of it...)
I already have an arduino yun but it is busy with a project, so I need something for the uno.
For what kind of projects could be better each of them? and what are the main differences between a shield and a breakout?
Also in the future I would do some projects with gsm, so this question could be similar ... gsm shield vs breakout.

Please note that stacking multiple shields sometimes results in conflict over their pin usage. When using regular breakout, can can connect the wires to any arduino pin you want, preventing these kinds of problems.

If you prototyping for a device intended for production then use breakout board with supposed WiFi module. Also if space is constraint then shield might be problem. For a hobby system use WiFi shield, which uses rather complicated circuit with AVR32 MCU, but you just plug-in and uses prooved libs. For production MCU would mean one more firmware flashing, upgrades, maintainance and higher price - from my point of view useless.

Thanks, I think it is better for me the shield, because I am novice and still learning. I will not develop a productive product.

Shields are in a form factor suited for direct attachment to the Arduino, but have fixed functionality for their connections. Breakout boards require more wiring work, but allow you to connect to any appropriate pins.

Could you please explain a little bit more about the communications protocols? Because I saw in this breakout " It uses SPI for communication (not UART!) " How does the shields communicates?

A breakout board usually has the sole purpose of making a single chip (gross generalization here...) available to the experimenter by "breaking out" its signal lines on to dedicated pins - header pins, for instance. It is only large enough for the chip and the printed circuit wiring to do this, and seldom adds any function beyond what the chip itself provides.
A "shield" is a larger board that usually plugs directly onto an Arduino board, matches its form factor, and is built for a dedicated more complex function, like a complete GPS system or cellular communication system (although some shields are left mostly blank to provide you the space to build your own device). They probably have several chips engineered and built into a complete plug-and-go sub-system.
One is to learn to use a chip or other device without having to solder up your own board, especially with surface mount devices. The other is a ready-to-go system building block.


text:
How to pass rx/tx led outputs to a shield
I have an Arduino Uno. I am building a custom shield and was wondering how I would connect two of the LEDs on the shield to the TX / RX LEDs on the Uno. Digital pins 0 and 1 seem obvious, but after further research, it appears that they are not for this.
In better terms, I want two LEDs on my shield that replicate the TX / Rx LEDs on the Arduino Uno.
How would I do this?

The TX/RX LEDs on the Uno are not connected to the main MCU but are instead connected to the USB communication chip, be it a FTDI or ATmega16U2. You would need to solder wires to the appropriate connections on the board and then connect them to the shield in question.

If you need just indicate data on TX/RX you can make simple circuit on shield bound to TX/RX lines.


text:
Help with a function that accepts different parameter types
I'm trying to create a function that prints out an XML tag with a value. I have the code below, but kind of stuck. I'd like to be able to call the function, and pass a value that could be a float, int, string or char. Appreciate any help.
char PingTime[6] = "3ms";
char PingText[60] = "ping reply blah blah";
float humidity = "40.56";
int DigialPin = 0;

PrintXMLTag(cl,"pingtime",PingTime);
PrintXMLTag(cl,"PingText",PingText);
PrintXMLTag(cl,"humidity",humidity);
PrintXMLTag(cl,"DigialPin",DigialPin);

void PrintXMLTag_DEC(EthernetClient cl, const char* tag, NotSure?? val)
{
  char tmp [100];
  StrClear(tmp,100);

  // If val type is float ----------------------
  int d1 = val; // Get the integer part
  float f2 = val - d1; // Get fractional part
  int d2 = trunc(f2 * 10000);// Turn into integer
  sprintf(tmp,"<%s>%d.%02d</%s>\n",tag,d1,d2,tag);
  // end float

  // If val type is string ----------------------

  // If val type is int ----------------------

  // If val type is char ----------------------

  cl.print(tmp);
}

Update, now converting the type to char before calling the PrintXML function resolves my initial issue. If I use the code below it seems to chew up a lot of memory, is there something obviously wrong? As a workaround I'm just printing the XML tags using cl.print and the memory usage is stable.
void PrintXMLTag(EthernetClient cl, char* tag,  char* val)
{
  char tmp [100];
  sprintf(tmp,"<%s>%s</%s>\n",tag,val,tag);
  cl.print(tmp);
  StrClear(tmp,100);
}

The simplest way is certainly to overload the PrintXMLTag() function by declaring it as many times as possible types for val variable; function overloading is perfectly supported in C++ 5not in pure C though).

Thanks all for the replies. Ive opted with simply converting the variables into type char before sending to the xml function. Seems to have done the trick, not sure why I didn't think of this prior to posting the question?

try using this example instead of iostream you can use iostream.h too..
#include <iostream>
using namespace std;

int sum (int a, int b)
{
  return a+b;
}

double sum (double a, double b)
{
  return a+b;
}

int main ()
{
  cout << sum (10,20) << '\n';
  cout << sum (1.0,1.5) << '\n';
  return 0;
}

take a look at: http://www.cplusplus.com/doc/tutorial/functions2/
template <typename SomeType>
SomeType sum (SomeType a, SomeType b)
{
  return a+b;
}

This appears to be what you want.

Not quite, because most types will need to be special-cased.

If your goal is really to print the value from XML, you don't need to worry about types, as long as you believe the XML to be correctly formed. The value in the XML file is already character string just print it. The converting from string to variable (sprintf()) and back to string (Serial.print() or printf()) is unnecessary.


text:
DateTime to string
For some reason I can't use the Time.h lib.
Can you guys tell me how to create a string from the datetime into a format like this:
yyyy.MM.dd:hh.mm.ss
2014.10.29:07.12.33

Seems odd that I can't find any examples of this.

That's because they all just print it.

What DateTime are you talking about? The type from RTClib? Of some other DateTime?

Is that what you want, mate?
char buf1[20];
DateTime now = rtc.now();
//Updated now.day to now.date
sprintf(buf1, "%02d:%02d:%02d %02d/%02d/%02d",  now.hour(), now.minute(), now.second(), now.date(), now.month(), now.year());

Serial.print(F("Date/Time: "));
Serial.println(buf1);

Great answer, except that now.day() does not exist – now.date() is correct. (I tried editing but SE requires edits to be at least 6 characters…)

thanks for edit bro.

If by DateTime you are referring to RTClib's DateTime (this is something you have to clarify in your question), then you can call unixtime() method on your DateTime object. The returned value is regular Unix "epoch" time, which can be used as time_t value with functions from <time.h> (and it's <time.h>, not <Time.h>).
For example, you can use ctime to convert Unix time_t value to a C-string, although the format of that string is different from the one you requested
DateTime dt;
...
time_t t = dt.unixtime();

const char *str = ctime(&t);
Serial.println(str);

On Arduino you also have ctime_r available to you as a reentrant version of ctime.
Or, if you need more flexibility with the format, you can use gmtime or localtime and then strftime, but this might be excessive, since struct tm generated by gmtime is in essence very similar to DateTime. You can simply use snprintf in a manner suggested in @şevket Karayılan's answer.
Nevertheless, note that strftime provides you with quite extensive formatting capabilities, which would take some effort to reimplement manually
DateTime dt;
...
time_t t = dt.unixtime();
struct tm *lt = localtime(&t);

char str[32];
strftime(str, sizeof str, "%Y.%m.%d:%H.%M.%S", lt);
Serial.println(str);

strftime(str, sizeof str, "%x %X", lt);
Serial.println(str);

strftime(str, sizeof str, "%F %T", lt);
Serial.println(str);

There's no built in function to do that, I'm afraid.
I suggest you create a method that will format the string like so. Something along the lines of:
void formatTime()
{
   string str = year() + "." + month() + "." + day() + ":" + hour() + "FILL IN THE REST";
}

What is string in this case? And the initializer expression is definitely not valid.

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


text:
Arduino as serial 'snoop' tool for 77 bits at 100k baud?
curious if a Arduino could be configured to read and serial print raw binary bits from a proprietary serial encoder used on machine tools and robots... if so, might have a lot of other possible uses.
I made up a 120 volt servo drive for manually moving big fanuc machine/robot servos, handy during rebuilding/service to be able to move a axis without a control...but the older drives read 4 gray code channels kinda like a set of halls for brushless commutation...on the serial versions, same drive could move the motor if I could decipher the commutation bits and output graycode to the drive... a tiny Arduino looks like a ideal little thing to try doing this.
Scoped out the signals long ago, kinda know where the bits are, but need to be able to actually print them out thru 90 degrees of shaft rotation to find the 12 steps for commutation required by the drive.
Arduino is new to me, but in the past few days have been quite impressed with its abilities. If anyone can suggest a way for Arduino to read a repeating 77 bit data stream at ~100K baud, I'm all ears... I think a 'serial snoop tool' with easily changed baud rates(including non-standard) and 'word length', then serial print out could be really handy. to prevent overflow in my case, could only do the serial print every X milliseconds, and I could just rotate slow enough to get a decent sample.

It should be possible, monitoring the I/O in software if not with the UART block.  But there are better tools for such a job, such as a CY7C68013A-based logic analyzer or possibly a bus pirate - the idea there is you stream an excess of data continuously to the PC, and then decode it in PC software.

thanks & I agree, that might be easier tool to read the data- but I also want to use the data to emulate 4 TTL outputs, and put it in the drive cable permanently...not really wanting to add a computer, just a small decoder- all I need is to extract the bits, and drive outputs emulating the old school brushless servo commutation tracks with a small stand-alone device. I truly think finding the signal and manipulating/outputting 4 digital signals will be the easy part- getting a 100K baudrate/77 bit word into the little Arduino (or another similar device with a few outputs) will be the hard part

Note that, for this to work, you'll need to maintain a 5V logic level signal for the UART to operate on.

not a problem, the drive has a regulated 5v supply for the encoder

getting 100k baud sorted out is my concern, as i dont know if i can use the serial monitor if using the rx pin to monitor the encoder- dont think so as it looks like the serial monitor will require standard 8 bit/'normal' baud selections...so may still need a logic analyzer to pick apart the bits initially. I'm thinking as a alternative, just to do a 115200 repeat dump of some 77 bit patterns I have already stored from a old laptop. just need to get the arduino to receive it.


text:
Multiple Stepper Motors in One Shield?

I need to construct 4 reactors for an experiment requiring mixing. We want to automate the mixing and at the same time reduce cost. can we connect multiple stepper motors with 5 or 6 wires on one shield version 2?

Please clarify: what shield model are you using, what stepper motors do you intend to use?

Is the picture related to question? I can see one 4-wire stepper motor only.

The board shown looks like it can handle two steppers, as a stepper requires two H bridges (if bipolar, or at least their low side switches if unipolar), so could replace the two PMDC motors requiring one each.

Depending on the shield you can connect an external powersource through mosfets or transistors (Depending on the size of the steppermotor).
But if it is smaller motors with a 12v powersource, i really don't se why you would do that, since stepper motor controllers cost about $2-$4 each. Being cost effective i think that writing this question would cost more than actually just go and buy 6-8 controllers. (Don't buy the shield ones, they are overly expensive)


text:
Modbus master slave
I need Help in two thing Here.
1)My main project is i have 23 hallsensors with analog output. There are connected to arduino UNO analog pins using 16:1 Mux or 8:1 mux circuit. The currently i can receive data properly with proper switching. Which are floating point values.
Second stage: Now this has to communicate via MODbus protocol .(here only transmission is pending)
2) Now I am in to transmission data. Here i am using basic library downloaded from
[Download link modbus library][1]
Now my setup is like this
I have arduino Board. RS485 sheild and USB to RS485 converter. Qmodbus software to view data.
I have uploaded the below code.
#include <ModbusRtu.h>

// data array for modbus network sharing
uint16_t au16data[16] = {
  3, 1415, 9265, 4, 2, 7182, 28182, 8, 0, 0, 0, 0, 0, 0, 1, -1 };

/**
 *  Modbus object declaration
 *  u8id : node id = 0 for master, = 1..247 for slave
 *  u8serno : serial port (use 0 for Serial)
 *  u8txenpin : 0 for RS-232 and USB-FTDI
 *               or any pin number > 1 for RS-485
 */
Modbus slave(1,0,0); // this is slave @1 and RS-232 or USB-FTDI

void setup() {
  slave.begin( 9600 ); // baud-rate at 19200
}

void loop() {
  slave.poll( au16data, 16 );
}

so i am expecting this answer if i am not wrong.
uint16_t au16data[16] = {
  3, 1415, 9265, 4, 2, 7182, 28182, 8, 0, 0, 0, 0, 0, 0, 1, -1 };

But i am getting data as below.
questions:
1) Whats making wrong to get below data??
2)If i want to store float values how can name uint16_t au16data[16] or changes to be made
3) Is there any working code ON modbus![OUTPUt of MODBUS][2]
Finally i got it working i can read The values. Now i am in second part. I have totally 20 values . currently i stored them as integer only. But my values are flaoting point.How to split real & floating value store in au16data[16] register.???
Assume i got my Sensor value converted as
*
CS=30.10
Int_CS=int(CS)
FLOAT_CS=(Int_CS-CS)*100
How to store the Int_CS & FLOAT_CS values in au16data[0]??

*

In Modbus protocol, coils are bits and registers are 16-bit unsigned integers.
Hence if you ask Modbus to read your au16data array as coils, and not as registers (which is what they actually are), then you'll get the binary representation for them with QModbus:
Your first register is 3 which is 0000 0000 0000 0011 in binary. Then when you read it as an array of 16 cils, you get these bit values, in reverse order (bit 0 is the lowest order bit and bit 15 is the highest order bit of your register); this is exactly what QModbus shos you:

First 2 bits are 1
All other bits are 0

Now regarding float values, if I remember correctly this is just not possible with Modbus protocol, hence you cannot do it out of the box.
What you can do, however, is to cast one float as 2 registers and transmit it this way, then it is up to the Modbus client to cast it back to a float; but QModbus will not do that for you as it strictly follows Modbus standard.

what i need to alter in above code to get like as array buffer.Is there any software avialble to view data as it is.uint16_t au16data[16] is register and save data in the form of bits.

When you choose a protocol (modbus) you need to comply with its limitations, or select another protocol!

If you want to see your array values as words not bits, then just tell QModbus to "read registers" instead of "read coils" that is all.

Ya it worked When i comment Read coil function to run only read register function In program. Now my question in second part How to keep real value and floating value in register of word au16data[16]


text:
Which side should I connect the resistor on?
I understand that when connecting an LED and a resistor in series; the resistor can be placed on any side of the LED as the current will remain same in a series connection. Please correct me if I'm wrong, but I was under the impression that conventionally the electrons flow from positive to negative. So shouldn't the resistor be placed before an LED to limit the flow of charge.
In this scenario the negative is connected ground and the positive to a power source. So I don't understand the chain Link analogy as well. Where the whole chain moves as a whole because here the flow ends with the GND right ?

Another way to look at it is this:Imagine the current flowing through the LED toward the resistor to be greater than the current flowing out of the resistor toward ground. The only way this could happen is if some of the charge - the difference due to the different currents - accumulated in the resistor. But that cannot happen forever, and not even for any appreciable length of time. (If it could, and did, the device would eventually fail - spectacularly!) So, because charge in must equal charge out over time (and over a very short period, at that) current in has to equal current out.

Charge per unit time.

Wow. That cleared things up. Thank you !! ... So resistance is basically the action of electrons moving slower as the electromagnetic force in the insulator is higher rite ?

Slower in the flow sense or electrons per unit time. And as I understand resistivity, it doesn't involve electromagnetic force but the availability of free electrons. More free electrons available to move through the material -> lower resistivity (and I'm somewhat beyond my knowledge here, but here is a section of a Wikipedia article that discusses it briefly).

Resistor on any side of led will intercept current flow.
Just use another analogy with water, tube and water tap.


text:
sprintf trouble
char cTime[22];

sprintf(cTime, "%04s/%02s/%2s:%02s:%02s:%02s", year(), month(), day(), hour(), minute(), second());

This sprintf line causes this error:**B0100000063f694Š
Could someone help me debug this?
Thank you.

%s is string macro but output of year(),... is probably an integer type. Use %d or %u macros in format.

Yes - try making each of the %-specifiers match the kind of conversion you want for each variable in the rest of the call. F/ex, %d converts an integer to a string in decimal radix, %f converts a double to a number with a decimal fraction, etc. In all cases, the output will be as characters; you don't need to specify that.


text:
TCS3200 color sensor not reading with delay lower then 4000 ms using TimerOne.h
I'm trying to get the color sensor TCS3200 to give color values with a delay lower than 4000 ms. I've found a library to interface the TCS3200 from this link.
I've modified the code to serve my needs and its works fine, almost! The before mentioned library uses TimerOne.h, which can not accept a delay lower than 4000 ms.
My question is therefor, if it is somehow possible to modify my code, so I can lower the delay?
This is my code:
#include <TimerOne.h>

#define S0     6
#define S1     5
#define S2     4
#define S3     3
#define OUT    2

int   g_count = 0;    // count the frequecy
int   g_array[3];     // store the RGB value
int   g_flag = 0;     // filter of RGB queue
float g_SF[3];        // save the RGB Scale factor

// Init TSC230 and setting Frequency.
void TSC_Init()
{
  pinMode(S0, OUTPUT);
  pinMode(S1, OUTPUT);
  pinMode(S2, OUTPUT);
  pinMode(S3, OUTPUT);
  pinMode(OUT, INPUT);

  digitalWrite(S0, LOW);  // OUTPUT FREQUENCY SCALING 2%
  digitalWrite(S1, HIGH);
}

// Select the filter color
void TSC_FilterColor(int Level01, int Level02)
{
  if(Level01 != 0)
    Level01 = HIGH;

  if(Level02 != 0)
    Level02 = HIGH;

  digitalWrite(S2, Level01);
  digitalWrite(S3, Level02);
}

void TSC_Count()
{
  g_count ++ ;
}

void TSC_Callback()
{
  switch(g_flag)
  {
    case 0:
         TSC_WB(LOW, LOW);              //Filter without Red
         break;
    case 1:
         g_array[0] = g_count;
         TSC_WB(HIGH, HIGH);            //Filter without Green
         break;
    case 2:
         g_array[1] = g_count;
         TSC_WB(LOW, HIGH);             //Filter without Blue
         break;
    case 3:
         g_array[2] = g_count;
         TSC_WB(HIGH, LOW);             //Clear(no filter)
         break;
   default:
         g_count = 0;
         break;
  }
}

void TSC_WB(int Level0, int Level1)      //White Balance
{
  g_count = 0;
  g_flag ++;
  TSC_FilterColor(Level0, Level1);
  Timer1.setPeriod(1000000);             // set 1s period
}

void setup()
{
  TSC_Init();
  Serial.begin(115200);
  Timer1.initialize();             // defaulte is 1s
  Timer1.attachInterrupt(TSC_Callback);
  attachInterrupt(0, TSC_Count, RISING);

  delay(4000);

  for(int i=0; i<3; i++)
    Serial.println(g_array[i]);

  g_SF[0] = 255.0/ g_array[0];     //R Scale factor
  g_SF[1] = 255.0/ g_array[1] ;    //G Scale factor
  g_SF[2] = 255.0/ g_array[2] ;    //B Scale factor

  Serial.println(g_SF[0]);
  Serial.println(g_SF[1]);
  Serial.println(g_SF[2]);
}

void loop()
{
  g_flag = 0;

    int R = int(g_array[0] * g_SF[0]);
    int G = int(g_array[1] * g_SF[1]);
    int B = int(g_array[2] * g_SF[2]);

    if((R>245) && (R<265) && (G>245) && (G<265) && (B>245) && (B<265))    // White
    {
      Serial.println("Color is white");
    }else if((R>24) && (R<44) && (G>56) && (G<76) && (B>95) && (B<115))  // Blue
    {
      Serial.println("Color is blue");
    }else if((R>56) && (R<76) && (G>107) && (G<127) && (B>80) && (B<100))  // Green
    {
      Serial.println("Color is green");
    }else if((R>171) && (R<191) && (G>154) && (G<174) && (B>71) && (B<91))  // Yellow
    {
      Serial.println("Color is yellow");
    }else if((R>77) && (R<97) && (G>46) && (G<66) && (B>43) && (B<63))  // Brown
    {
      Serial.println("Color is brown");
    }else if((R>39) && (R<59) && (G>38) && (G<58) && (B>36) && (B<56))  // Brown dark
    {
      Serial.println("Color is brown dark");
    }else if((R>20) && (R<40) && (G>43) && (G<63) && (B>48) && (B<68))  // Turkis
    {
       Serial.println("Color is turkis");
    }else if((R>39) && (R<59) && (G>77) && (G<97) && (B>55) && (B<75))  // Green
    {
       Serial.println("Color is green");
    }else
    {
      Serial.print("Red = ");
      Serial.println(R);
      Serial.print("Green = ");
      Serial.println(G);
      Serial.print("Blue = ");
      Serial.println(B);

    };

   delay(4000);
}

I've searched all over the net and didn't find any good solutions, where I can still specify the colours by hex degree.
All help would be highly appreciated!

You can increase the frequency (x10) by setting S0 HIGH and S1 LOW. Then you can change the timerone frequency from once a second to once every 100ms (Timer1.setPeriod(100000);). Then you can change your delay to delay(400). PS I think you only need to wait for a bit over 3 timerone cycles, so delay(350) should also work.

Try looking at the datasheet. No need to understand everything in there.

You can increase the frequency (x10) by setting S0 HIGH and S1 LOW. Then you can change the timerone frequency from once a second to once every 100ms (Timer1.setPeriod(100000);). Then you can change your delay to delay(400).
PS I think you only need to wait for a bit over 3 timerone cycles, so delay(350) should also work.


text:
Adafruit CC3000 WiFi Module working together with MFRC522 RFID Module Issues both SPI over Arduino
I'm asking if how can I implement this one. I'm aware about multiple devices being connected over SPI, like having to select individual SS pin for each. Adafruit's CC3000 works fine alone along with the default Adafruit library. CC3000 uses SPI. MFRC522 RFID module by sonmicro (bought at Sparksfun) uses SPI too. It works fine too, independently. But whenever I connect them together, only WiFi works perfectly. I dont want to turn on and off the wifi to make way for the RFID to communicate since it takes some time for it to be connected in a wireless network. I want the two to work synchronously (or having to be scheduled but really fast that's unnoticeable by the user)
here's my code as of now. i cannot post it here as strange things happen i don't know why haha https://drive.google.com/file/d/0B0bZsYo0xMH8YV9uWXJaRFdPT3M/view?usp=sharing
I'm thinking of replacing the RFID with SonMicro's SM130 RFID Module w/ SparkFun Eval board with UART (convertible to I2c) or Adafruit's PN532 with I2c by default. Are these okay to be paired with SPIs like the CC3000? Or should I change CC3000 with the Official WiFi module (UART) or WiFly Module (SPI-to-UART)

I couldn't get your code to download so this might be wrong, but it sounds like the modules are running different SPI modes: http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus#Mode_numbers
I had this problem a few years ago. You'd expect SPI to be SPI, but it comes in four different flavours and they won't talk to each other on the same bus. Unfortunately there's no solution but to replace the modules; the Arduino can only run one SPI bus, so can only talk to one of these modules at a time.
However you can run UART and I2C or UART and SPI concurrently by using SoftwareSerial (don't use the native Tx/Rx pins, bad things happen).
So your best bet is to switch to modules that use I2C or UART. Personally I'd use UART, simply for the simplicity of having two separate connections and a higher data rate.

thanks for the tip. I'll be trying that. but how would I use UART with SPI? THere are pin assignments that the two share. I'm thinking using of SparkFun's SM130 Eval Board with the CC3000, but CC3000 have SPI so 11,12,13 are exclusive for SPI, although it has ICSP header also for SPI, (would this header make the pins 11,12,13 free?)

You can use SoftwareSerial (http://arduino.cc/en/Reference/softwareSerial) to declare new UART connections from almost any pin (on the Uno, some limitations on other boards). I can't remember if the SPI on the ICSP header is simply the same as pins 11,12,13 or if it's used for the Atmega16U2. Either way it's not going to free up 11,12,13.


text:
Rotary encoder on Uno and interrupts issue
This question is regarding a project using an Arduino Uno.
I have one of these quadrature rotary encoders.
I'm using a slightly modified version of the code from the article, Quadrature Encoder too Fast for Arduino (with Solution), which uses a library called digitalwritefast.
My version of the code on pastebin - I modified to use different pins for the Uno and a single encoder:
#include <digitalWriteFast.h>  // library for high performance reads and writes by jrraines

#define c_LeftEncoderInterrupt 0
#define c_LeftEncoderPinA 2
#define c_LeftEncoderPinB 3

volatile bool _LeftEncoderBSet;
volatile long _LeftEncoderTicks = 0;

void setup()
{
  Serial.begin(115200);
  pinMode(c_LeftEncoderPinA, INPUT);
  digitalWrite(c_LeftEncoderPinA, LOW);
  pinMode(c_LeftEncoderPinB, INPUT);
  digitalWrite(c_LeftEncoderPinB, LOW);
  attachInterrupt(c_LeftEncoderInterrupt, HandleLeftMotorInterruptA, RISING);
}

// Interrupt service routines for the left motor's quadrature encoder
void HandleLeftMotorInterruptA()
{
  _LeftEncoderBSet = digitalReadFast2(c_LeftEncoderPinB);   // read the input pin
  _LeftEncoderTicks -= _LeftEncoderBSet ? -1 : +1;
}

void loop()
{
  Serial.print(_LeftEncoderTicks);
  Serial.print("\n");
  delay(20);
}

I am attaching output A of the encoder to pin 2 and output B to pin 3.
This setup works fine and I can detect turns in both directions, but my problem is, if I set pin B to any other pin, I get positive direction only (regardless of the direction in which the encoder is turned) - as if pin B isn't plugged in at all (I am modifying c_LeftEncoderPinB accordingly).
I'm assuming that this is something to do with pin 3 being the only other interrupt pin on the Uno (I can't see anything else unique about that pin). Yet I don't know why because the interrupt is on pin A (we're reading the value of pin B in that interrupt, though).

The code you started from was never meant for bi-directional rotary encoders. I'd suggest looking for a proper rotary encoder library (that also handles de-bouncing). That might safe you some headaches.

What happens if you use digitalRead instead of digitalReadFast2?

Please do not use pastebin on SE, it is not recommended, in case the link dies (there is a post about this on Meta somewhere). It is far better, and easier for us, if you just post the code directly into your question/answer.

OK embarrassingly it turns out my wiring was wrong! I was going astray as it was working in both directions as described, even when only one of the outputs was connected, as long output B was connected to an interrupt. Once the wiring was sorted everything worked perfectly, in both directions, using just one of the interrupt ports.

When turning one way, A is asserted, then B is asserted, then A is deasserted then B is deasserted. You can detect this because A is asserted first, even if you can't tell when B has changed. But if you turn the opposite way then you fail to detect the initial assertion of B, and the code fails.
What you may be able to do is use PinChangeInt to capture the pin change interrupt rather than an external interrupt. This should allow you to use almost any I/O pins on the Uno for the encoder.

Hi Igancio. Could you clarify - what is it exactly that causes the detection failure on pins other than pin 3? I was assuming that it being an interrupt pin didn't make any difference since we're not actually setting an interrupt on this pin?

The code needs the interrupt in order to work. No interrupt, no work.

:( I don't understand. The interrupt is working on pin 2. I'm reading from pin 3 after the interrupt, not setting an interrupt on it directly. In the original code, the author is using pins 19 (A) and 25 (B) on an arduino mega. Pin 25 on the Mega is not an interrupt pin either

My first thought is that something else is off because there is no reason that shouldn't work.  It will of course only count 1/4 of the ticks since that's how it was designed to work for very fast motors.  I can't comment yet but to Gerben above, I think it is meant to be bidirectional as indicated by the ternary operator.  My guess is the problem is with the digitalReadFast library and I would be interested to know if this works when using digitalRead() instead.
My second thought is that this is usually not the best way to do things.  Firstly, you would need a really fast motor for the read fast function to matter.  Secondly, you're sacrificing resolution by only using one interrupt instead of two.  The more generally accepted method is to attach both pins of the encoder to an interrupt.  Alternatively, you could use pin change interrupts which allow any pin to be used as an interrupt.  However, there are only 3 interrupt service routines on the Uno, one for each port of pins.  Whenever one pin on that port triggers, the ISR triggers and you need to keep track of the pin states in order to do anything with it.  Here's a good example of the first and info on the second method.

authors: Ελπινίκη Μαρούλη

authors: Никита Чаузов


text:
Homebrew Arduino using ATMEGA328P, ISP or ICSP?
I plan on creating a homebrew Arduino breakout board using the ATMEGA328P smd version. I'm geeting confused by the wealth of information out there as to whether I should be using ICSP or ISP to program it. It is a blank chip, aka no Arduino bootloader on it yet. I'd rather not have to buy a specialized programmer to burn the bootloader, I do have another Arduino I could use to burn the bootloader and upload sketches to it with.
So the question is; Do I use ISP or ICSP, or both?

To program it you could use an ISP programmer. In which case you would not need the bootloader. You can use an Arduino as an ISP programmer, but that's not really a long term solution, as you can no longer use the arduino for anything else.
The other option is to program it using a usb-to-serial. In this case you do need the arduino bootloader. To program this bootloader (once) you can use the above method, using an arduino board.
Third option would be implement USB into the bootloader, just like the completely Open Source Pro Trinket (bootloader and schematic). You'd have to add some resistors, zener diodes and a usb plug (just strip an old usb cable). A bit more technical and challenging, but definitely the cheapest

Using an Arduino as an ISP in no way means you cannot use it for other purposes - load the ISP sketch, add your reset defeat component, use it to ISP your target, remove the component, load a different sketch...

ICSP is used for PICs, not AVRs. Use ISP, which can be performed either by an Arduino via ArduinoISP or by a dedicated programmer.

I'm currently holding an Arduino Uno that has a 6 pin male header that says on the silk screen next to the header "ICSP".

Yeah, it's mislabeled. It's supposed to read "ISP".

The OP question still remains I think: I would interpret it as: "should I use a programmer or an Arduino as ISP? What are the advantages of each?"

I think both terms mean pretty much the same thing. In-System-Programmer vs In-Circuit-Serial-Programmer. I didn't know one was PIC, and the other AVR. I usually call it ICSP, as ISP sounds a lot like SPI (and both use MISO, MOSI, SCK).

@Gerben: At a high level, I agree. At a low level, they are subtly different (ICSP more resembles AVR's HVSP at the electrical level, but uses different signaling).

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


text:
Adafruit gps breakout module help
I am intending to show the initial, searching for signal..., screen until the location is updated and then show the location on the lcd. However, even after the led on the gps indicates a satellite fix, the screen never leaves the searching for signal screen. Any help would be greatly appreciated-- very new to microcontroller programming. Sorry for the poorly formatted code block as well, I am in a rush.
Thanks in advance.
#include <SoftwareSerial.h>
#include <LiquidCrystal.h>
#include <TinyGPS++.h>

#define RXPin 2
#define TXPin 3
#define GPSBaud 4800

SoftwareSerial ss(RXPin, TXPin);
TinyGPSPlus gps;
LiquidCrystal lcd(12, 11, 10, 7, 6, 5, 4);

double latt;
double lon;
int screen;

void setup(void);
void loop(void);
void readGPS(void);
void update(void);
void render(void);

void setup() {
     //variable initialization
     latt = 0.0;
     lon = 0.0;
     screen = 0;

     //lcd initial setup
     pinMode(9, OUTPUT);
     analogWrite(9, 100);
     pinMode(13, OUTPUT);
     digitalWrite(13, HIGH);

     //display intial screen
     lcd.begin(16,2);
     lcd.clear();
     lcd.setCursor(0,0);
     lcd.print("Searching for");
     lcd.setCursor(6,2);
     lcd.print("Signal ...");
     ss.begin(GPSBaud);
}

void loop() {
    readGPS();
    update();
}

/** Receives data from the gps if available */
void readGPS() {
    while (ss.available() > 0) {
        gps.encode(ss.read());
    }
}

/** Processes the data read by readGPS() */
void update() {
    if (gps.location.isUpdated()) {
        latt = gps.location.lat();
        lon = gps.location.lng();
        render();
    }
}

/** Displays the current screen on the lcd */
void render() {
    if (screen == 0) {
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Lat:");
        lcd.print(latt);
        lcd.print(" Lng:");
        lcd.print(lon);
        lcd.setCursor(0,1);
        lcd.print("Sats:");
        lcd.print(gps.satellites.value());
    }
}

Does this also happen when the Arduino is NOT connected to the computer? I've had problems with LCD displays when I leave the Arduino connected. I have to disconnect from the PC and then the display comes to life.

Have you tried this outside? A GPS can get a partial lock (I frequently get time/date signals without location signals) which would cause the lock light to turn on, but you wouldn't be receiving latitude and longitude yet. If you can I would output the GPS string to Serial as well and keep an eye on it to see if you are getting lat/long data or if that part is missing.

Adafruit GPS breakout has their own library setup.
Below is the code I use for my telemetry. Notice I'm using HardwareSerial though.
You can just change that into SoftwareSerial.
#include <SoftwareSerial.h>
#include <Adafruit_GPS.h>
#define GPSECHO false // Disables GPS breakout debug

boolean usingInterrupt = false;

HardwareSerial gpsSerial = Serial1;
Adafruit_GPS GPS(&Serial1);

SoftwareSerial XBee(2, 3); // For wireless

unsigned int REFRESH = 20;

double lat_deg, lon_deg, lat_min, lon_min;
char lat, lon;

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

  GPS.begin(115200);
  GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
  GPS.sendCommand(PMTK_SET_NMEA_UPDATE_5HZ); // Either 1HZ or 5HZ
  GPS.sendCommand(PMTK_API_SET_FIX_CTL_5HZ);
  GPS.sendCommand(PGCMD_ANTENNA);

  useInterrupt(true);
}

SIGNAL(TIMER0_COMPA_vect)
{
  char c = GPS.read();
#ifdef UDR0
  if (GPSECHO)
    if (c) UDR0 = c;
#endif
}

void useInterrupt(boolean v)
{
  if(v)
  {
    OCR0A = 0xAF;
    TIMSK0 |= _BV(OCIE0A);
    usingInterrupt = true;
  }
  else
  {
    TIMSK0 &= ~_BV(OCIE0A);
    usingInterrupt = false;
  }
}

void loop()
{
  if(GPS.newNMEAreceived())
  {
    if(!GPS.parse(GPS.lastNMEA()))
    {
      writeData(1, true);
      Serial.print(GPS.hour, DEC); Serial.print(F(","));
      Serial.print(GPS.minute, DEC); Serial.print(F(","));
      Serial.print(GPS.seconds, DEC); Serial.print(F(","));
      Serial.print((int)GPS.fix); Serial.print(F(","));
      Serial.print((int)GPS.fixquality); Serial.print(F(","));
      Serial.print(F("-999")); Serial.print(F(","));
      Serial.print(F("-999")); Serial.print(F(","));
      Serial.print(F("-999")); Serial.print(F(","));
      Serial.print(F("-999")); Serial.print(F(","));
      Serial.print(F("-999")); Serial.print(F(","));
      Serial.print(F("-999"));
    }
    else if(GPS.fix)
    {
      writeData(1, true);
      parseGPS(GPS.latitude, GPS.longitude);
      Serial.print(GPS.hour, DEC); Serial.print(F(","));
      Serial.print(GPS.minute, DEC); Serial.print(F(","));
      Serial.print(GPS.seconds, DEC); Serial.print(F(","));
      Serial.print((int)GPS.fix); Serial.print(F(","));
      Serial.print((int)GPS.fixquality); Serial.print(F(","));
      Serial.print(lat_dd, 8); Serial.print(F(","));
      Serial.print(lon_dd, 8); Serial.print(F(","));
      Serial.print(GPS.speed); Serial.print(F(","));
      Serial.print(GPS.angle); Serial.print(F(","));
      Serial.print(GPS.altitude); Serial.print(F(","));
      Serial.print(GPS.satellites);
    }
  }
  delay(REFRESH);
}

void parseGPS(float _latitude, float _longitude)
{
  lat_deg = (int) (_latitude / 100);
  lon_deg = (int) (_longitude / 100);

  lat_min = _latitude - (lat_deg * 100);
  lon_min = _longitude - (lon_deg * 100);

  lat_dd = (double) lat_deg + ((double) lat_min / 60);
  lon_dd = (double) lon_deg + ((double) lon_min / 60);

  lat = GPS.lat; lon = GPS.lon;

  if (lat == 'S') lat_dd = -lat_dd;
  if (lon == 'W') lon_dd = -lon_dd;
}

void writeData(float data, boolean next)
{
  Serial.print(data);
  if (next) Serial.print(F(","));
}


text:
Unintended reaction: Sketch makes LEDs turn on and of randomly/LEDs don't react
Update: This piece of code does not do the same as the one in the right answer, it also reacts when one lets go of the button.
int button_prev = 0;
int button = 0;

void loop(){

    button_prev = button;

    button = digitalRead(12);

    if (button_prev != button) {

      digitalWrite(act_pin[j], HIGH);

      j = (j+1) % 5;

    }
}

I printed out j and it seems like, instead of counting up +1 everytime the button is pressed once, it turns +1 and then +1 again which makes two LEDs at a time turn on.
But I don't see where the behavior of j comes from...
[Update: There was a mistake in the code which caused the random behavior, but now, nothing happens when I push the button.]
[I wrote a sketch which is supposed to make the Arduino turn one of five LEDs on one after another every time I press the switch.
But instead of turning one LED on after another, directly after upload it just makes them turn on and of at random. I don't push the button.
Serial.println as well just spits out one character, similiar looking to a d.]
Can anyone point out my mistake to me?
This is the circuit

and this is the old code of the sketch
int act_pin[6] = {A0, A1, A2, A3, A4};

int j = 0;

void setup(){

  Serial.begin(9600);

  for (int k = 0; k < 5; k++) {

     pinMode(act_pin[k], OUTPUT); //sets analog pins A0 - A4 as output

     digitalWrite(act_pin[k], LOW); //turns LEDs connected to A0 - A4 off

     pinMode(12, INPUT); //sets pin connected to button as input

}

}

void loop(){

  char button = {digitalRead(12)}; //stores if the button was pressed

  Serial.println(button);

  if(button == HIGH){

    digitalWrite(act_pin[j], HIGH); //turns LEDs on A0 - A4 on one after one with every button press

    j = (j+1) % 5; //makes digitalWrite jump to the next LED next time the button is pressed and limits it to 4

    button = LOW; //turns the button's pin low again, so nothing will happen until the button is pressed again
}

}

Other than the fact that you don't do any debouncing?

Care to explain to me what you mean by debouncing? (And if it could be the cause of the problem.)

http://en.wikipedia.org/wiki/Switch#Contact_bounce

Okey, I edited the question: I don't even press the button before the failure happens. Also: "The effect is usually unimportant in power circuits, but causes problems in some analogue and logic circuits that respond fast enough to misinterpret the on‑off pulses as a data stream." and I am not using an analog input or output(I do use the analog pins, right, but with digitalWrite).

A MCU is a giant logic circuit.

The debouncing that you should be worried about is that your code loops so fast, even pressing the button for an instant activates the "button is pressed" code multiple times. you need to recognize when the button has turned from off to on, not just when it is pressed.

You might want to add a delay, or the leds will turn on, one after another, faster than your eyes can see.

@BrettM I already thought that this could be a problem, but as Gerben said, this would make the lamps turn on very fast. Right now, the lamps do not react at all.

@Gerben See the comment above this one.

change "button" to a boolean and the serial output will start making sense; with more understandable serial output how about putting a large delay in the loop (1s maybe?) and then looking at the output to see if button is reacting correctly.

@BrettM I put a delay of 2 sec at the end of the if. When I output button as a boolean, I get 0 until I press it, when, because of the delay, the output stops, then, I get a 1 and then it goes back to writing 0. So I think the button is reacting correctly.

I think you're looking for the action (in pseudo-code):
ONCE (Button Pressed):
    Light LED j;
    j++

But you have an IF(button) in a Loop{}. Something like:
WHILE (Button Pressed):
    Light LED j;
    j++

So when you press the button j will increment every iteration of Loop {}  (very fast) and you won't be able to see the LEDs changing. Your 'button = LOW' is not effective because 'button' gets set again the next time if the button is still pressed.
Try printing j instead of button at the line:
Serial.println(j);

and that should highlight the problem.
I would implement a ONCE(Button Pressed) function by observing the previous button state and checking it has changed from LOW to HIGH.
    button_prev = button;
    button = digitalRead(12);
// Check if button changed from LOW to HIGH
    if (!button_prev && button) {
    ...code
    }

EDIT: Dealing with Contact Bounce
Switches are mechanical so they don't switch cleanly. This is called contact bounce and means the switch switches on/off very rapidly for about 10ms or so after the contact has been pressed or released.
See Measuring Switch Bounce

You can deal with it quite simply in the code as follows (pseudo code) just by waiting for the bounce to dissapear and checking the button is still pressed:
ONCE (Button Pressed):
   WAIT(20ms)              // wait for the bounce to stop
   IF(Button Pressed):     // Ensure the button is still pressed
    ...code...

Try the following Arduino Code:
    button_prev = button;
    button = digitalRead(12);
// Check if button changed from LOW to HIGH
    if (!button_prev && button) {
       delay(20);                 // Wait for debounce
       if(digitalRead(12))  {     // Make sure the button is still pressed
        ...code
       }
    }

So, I wrote a piece of code which works so far, as the LEDs do react to the button, but somehow, they always turn on two at a time. See edit.

I found the error. I wrote the piece of code different from yours because I didn't fully understood your if statement when I first read it(hadn't used boolean operators in C yet), but I thought my code does the same as yours, while it does not. It also reacts when I let the button go. You solution is right, thank you!

You say the LEDs also change when you release the button? That's just contact bounce which means the switch bounces on/off for about 10ms after you've pressed it (on or off) due to the mechanical nature of the switch contacts. I'll add a section to my answer on how to deal with that.

No, that wasn't because of the bouncing, but because of a mistake of mine in the if statement. It became true if I pushed button, but as well when I released it but I used your statement and now it works just fine. What, indeed, is caused by debouncing, is that the program sometimes processes two pins at a time instead of just one.

Thanks for the code, I think I'll rather use that one instead of the code from the Arduino site(which is probably basically the same, but it seems far more complicated to me).

Your way of debouncing works, I didn't think it would be that easy to do, thanks! :) (Would mark your answer right a second time, if I could.)

Your code has a serious bug here:
if(button == HIGH){

    digitalWrite(act_pin[j], HIGH);

    j = j+1;

    button = LOW;
}

You increment j without any boundary so it will have the following cycling values:
0, 1, 2, 3 ... 32767, -32768, -32767 ... -1, 0 ...

Hence, quickly act_pin[j] will return garbage...
The solution is easy, you must limit j to [0,1,2,3,4], just replace the j = j + 1 line as follows:
j = (j + 1) % 5;

% is the modulo integral operation that will give you the reminder of dividing j by 5, which is always strictly less than 5, and it cycles as you want.

Thanks, I did that, this does not solve the problem about the lamps not reacting. (Actually in the whole context of the project it wouldn't make sense to press the button more than five times, so I did not thought about a limit, but still, its much cleaner like this, thank you!)

if(button = HIGH)

Oops.
if (button == HIGH)

And see the Debounce example sketch to learn how to debounce inputs.

Oh...okey. I am a blind man. The random on-off stopped. But now nothing happens when I push the button, could this be because of this debouncing? I am just wondering because I did something similar with a button before(the second project in the starter book), and there was no concern about debouncing whatsoever.

As they say there: "Without debouncing, pressing the button once can appear to the code as multiple presses." but nothing happens when I press the button.

None of the LEDs turn on?

Yes, none. I also tried pushing longer, but I get no reaction.

The braces around the call to digitalRead() are suspect. Remove them.

Changes nothing. I also tried giving button a fixed length of [6](HIGH + \0) but that returns the same result.

authors: Вадим Клементьев


text:
Problem with piezo readings and Arduino Due
I'm using 1mOhm resistor in parallel to a piezo that is connected to analog1 pin on the Due,

and the following code to observe the readings in the serial monitor:
int piezo = A0;
int threshold = 200;//anything over 200 means I've hit the piezo

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

//this part checks if the threshold has been reached and then writes the strenght of the signal

void loop(){
    int piezoVal = analogRead(piezo);

    if (piezoVal>threshold){
        Serial.println(piezoVal);

        delay(10); //delay is used to prevent from getting multiple values one after another, usually 3-4
    }
}

The things that bother me are:

if I do not use threshold, then I am constantly getting readings from the piezo, even if the threshold is slightly below 200.
if I do not use delay, then I'm getting getting multiple values one after another
and the strangest thing is while I hit the mouse pad that covers the piezo, the readings in the serial monitor are not matching the force being used to trigger the piezo. Sometimes they stay the same, sometimes they reach 6-700 after I directly touch the piezo, sometimes I hit really hard and I only get some slight increase (for ex. from 225 to 229).

This doesn't make sense to me. I think the stronger the vibration, the higher the values should be. Cause I've tried with two different piezos and different resistors (1mOhm, 1.2 mOhm and 1.5 mOhm) and I'm still getting the same result. I bought the Due few days ago in order to build a drum kit, and I have no problem with sending midi notes to a DAW, but this piezo sensitivity thing is driving me crazy. Any suggestions?

The problem is timing.  When you tap or hit the sensor it produces an impulse response: a signal that increases to a peak, then decays back to zero.  You are expecting the code to capture the peak value.  Your code is spinning in loop() as quickly as possible, but captures just the first point above the threshold. The signal can still be increasing when you capture and print.
So imagine this stream of signal values
time  signal   analogRead()
      at pin   occurs
----  ------   --------
 1     190      190
 2     190
 3     199
 4     210
 5     220      220 - trips threshold, prints and then waits
 6     230
 7     260
 8     280
 9     320      (this point occurs during delay())
 10    280
 11    260

The same exact signal, but at a slightly different time could be read different by the code:
time  signal   analogRead()
      at pin   occurs
----  ------   --------
 1     190
 2     190
 3     199      199
 4     210
 5     220
 6     230
 7     260      260
 8     280
 9     320      (closer, but still did not read the peak)
 10    280
 11    260

So the strategy of catching the first point above the threshold makes it unlikely you can capture the peak value.  There are two ways forward: hardware or software.
You could use electronics that latches the maximum value.  If you search "peak hold circuit" you will find many circuits that would capture and hold the peak.  That frees the Arduino to somewhat lazily spin in the loop and still be able to accurately capture the peak.  Once it sees the value is no long increasing, it resets the peak hold and goes back to waiting.
You could use code to capture the peak. Something along the lines of this psuedo code:
lastreading = analogread()
if(lastreading > threshold) {
  peakreading = lastreading
  keeplooking = true
  while(keeplooking) {
    nextreading = analogRead()
    if(nextreading > lastreading) {
      // the signal is increasing, save this and see if next point is even higher
      peakreading = nextreading
      lastreading = nextreading
    }
    else {
      //signal is decreasing, the peak is over
      keeplooking = false
    }
  }

This software approach could still miss a sharp peak that occurs between analogRead()'s, but may be good enough for your use.

I very much appreciate your help. Since I'm a total beginner, I expect things to run smoothly :). I'll definitely dive into this peak filtering and share the results.


text:
Modbus slave data into word

I have simple code. The library downloaded from github:smarmengol/Modbus-Master-Slave-for-Arduino.
I wanted to store floating point. In the code blow, I type casted to integer value. As I know uint16_t au16data[30]; is integer
#include <avr/wdt.h>
#include"glob.h"

#define ID   1
int8_t state = 0;
Modbus slave(ID, 0, 0);
unsigned long tempus;
// data array for modbus network sharing
uint16_t au16data[30];

void Take_Reading()
{
  for(row=0;row<9;row++)
  {
  int k=(8*array[row][0]+4*array[row][1]+2*array[row][2]+1*array[row][3]);
    digitalWrite(Enablepin,array[row][0]);
    digitalWrite(SO_enable,array[row][1]);
    digitalWrite(S1_enable,array[row][2]);
    digitalWrite(S2_enable,array[row][3]);
   //delay(100);
    Sensor_Value0=analogRead(A0);
    Sensor_Value1=analogRead(A5);
   Mux1_array[row]=(Sensor_Value0 * ARDUINO_ANALOG_SCALING);
   Mux2_array[row]=(Sensor_Value1 * ARDUINO_ANALOG_SCALING);

   Current_Value1[row]=  (Mux1_array[row]*40)-98;
   Current_Value2[row]=  (Mux2_array[row]*40)-98;

  }
}

void setup()
{
     wdt_enable(WDTO_8S);
   slave.begin( 9600 );
  tempus = millis() + 100;
  pinMode(3,OUTPUT);
  pinMode(SO_enable, OUTPUT) ;// pin can enable/disable using digital IO 7 of arduino
  pinMode(S1_enable, OUTPUT) ;// pin can enable/disable using digital IO 6 of arduino
  pinMode(S2_enable, OUTPUT) ;// pin can enable/disable using digital IO 5 of arduino
  pinMode(Enablepin, OUTPUT) ;// pin can enable/disable using digital IO 4 of arduino
  pinMode(A0, INPUT) ;
  pinMode(A5, INPUT) ;

//  Serial.begin(9600);
}

void loop()
{
  digitalWrite(3,HIGH);
// wdt_reset();
 Take_Reading();
 state = slave.poll( au16data,30 );
  if (state > 4) {
    tempus = millis() + 50;
    digitalWrite(13, HIGH);
  }
  if (millis() > tempus) digitalWrite(13, LOW );

Modbus_call();

}

void Modbus_call()
{

/*reading of coil where i can succefully read value*/
  au16data[0]=(int)Current_Value1[0];
  au16data[1]=(int)Current_Value1[1];
  au16data[2]=(int)Current_Value1[2];
  au16data[3]=(int)Current_Value1[3];
  au16data[4]=(int)Current_Value1[4];
  au16data[5]=(int)Current_Value1[5];
  au16data[6]=(int)Current_Value1[6];
  au16data[7]=(int)Current_Value1[7];
  au16data[8]=(int)Current_Value1[8];
  au16data[9]=(int)Current_Value2[0];
  au16data[10]=(int)Current_Value2[1];
  au16data[11]=(int)Current_Value2[2];
  au16data[12]=(int)Current_Value2[3];
  au16data[16]=(int)Current_Value2[4];
   au16data[17]=(int)Current_Value2[5];
   au16data[18]=(int)Current_Value2[6];
   au16data[19]=(int)Current_Value2[7];
 uint16_t calcCRC( au16data[15]);
     au16data[13] = slave.getInCnt();
  au16data[14] = slave.getOutCnt();
  au16data[15] = slave.getErrCnt();

 }

Conversion method as below.
CS=30.10
Int_CS=int(CS)
FLOAT_CS=(Int_CS-CS)*100

How to store the Int_CS & FLOAT_CS values in au16data[0]??

I have change code accordingly.

But I get zero. After some time its values don't even show
#include <avr/wdt.h>
#include"glob.h"

#define ID   1
int8_t state = 0;
Modbus slave(ID, 0, 0);
unsigned long tempus;
// data array for modbus network sharing
uint16_t au16data[5];
float auFloatData[30];
void Take_Reading()
{
  for(row=0;row<9;row++)
  {
  int k=(8*array[row][0]+4*array[row][1]+2*array[row][2]+1*array[row][3]);
    digitalWrite(Enablepin,array[row][0]);
    digitalWrite(SO_enable,array[row][1]);
    digitalWrite(S1_enable,array[row][2]);
    digitalWrite(S2_enable,array[row][3]);
   //delay(100);
    Sensor_Value0=analogRead(A0);
    Sensor_Value1=analogRead(A5);
   Mux1_array[row]=(Sensor_Value0 * ARDUINO_ANALOG_SCALING);
   Mux2_array[row]=(Sensor_Value1 * ARDUINO_ANALOG_SCALING);

   Current_Value1[row]=  (Mux1_array[row]*40)-98;
   Current_Value2[row]=  (Mux2_array[row]*40)-98;

  }
}

void setup()
{
     wdt_enable(WDTO_8S);
   slave.begin( 9600 );
  tempus = millis() + 100;
  pinMode(3,OUTPUT);
  pinMode(SO_enable, OUTPUT) ;// pin can enable/disable using digital IO 7 of arduino
  pinMode(S1_enable, OUTPUT) ;// pin can enable/disable using digital IO 6 of arduino
  pinMode(S2_enable, OUTPUT) ;// pin can enable/disable using digital IO 5 of arduino
  pinMode(Enablepin, OUTPUT) ;// pin can enable/disable using digital IO 4 of arduino
  pinMode(A0, INPUT) ;
  pinMode(A5, INPUT) ;

//  Serial.begin(9600);
}

void loop()
{
  digitalWrite(3,HIGH);
// wdt_reset();
 Take_Reading();
 state = slave.poll( au16data,5 );
  if (state > 4) {
    tempus = millis() + 50;
    digitalWrite(13, HIGH);
  }
  if (millis() > tempus) digitalWrite(13, LOW );

Modbus_call();

}

void Modbus_call()
{

/*reading of coil where i can succefully read value*/
  auFloatData[20]=Current_Value1[0];
  auFloatData[21]=Current_Value1[1];
  auFloatData[22]=Current_Value1[3];
  auFloatData[4]=Current_Value1[4];
  auFloatData[5]=Current_Value1[5];
  auFloatData[6]=Current_Value1[6];
  auFloatData[7]=Current_Value1[7];
  auFloatData[8]=Current_Value1[8];
  auFloatData[9]=Current_Value2[0];
  auFloatData[10]=Current_Value2[1];
  auFloatData[11]=Current_Value2[2];
  auFloatData[12]=Current_Value2[3];
  auFloatData[16]=Current_Value2[4];
   auFloatData[17]=Current_Value2[5];
   auFloatData[18]=Current_Value2[6];
   auFloatData[19]=Current_Value2[7];
uint16_t calcCRC( au16data[3]);
     au16data[1] = slave.getInCnt();
  au16data[2] = slave.getOutCnt();
  au16data[3] = slave.getErrCnt();

 }

if you need 2 numbers after comma then you can uint16_t x =CS*100 it will store 3010. When extracting from uint to float float y = (float)x/100.

Sizes

Integer Types (int, long and long long)
Size of Boolean type is 1 byte(s)
Number of bits in a character: 8
Size of character types is 1 byte
Signed char min: -128 max: 127
Unsigned char min: 0 max: 255
Default char is unsigned
Size of short int types is 2 bytes
Signed short min: -32768 max: 32767
Unsigned short min: 0 max: 65535
Size of int types is 4 bytes
Signed int min: -2147483648 max: 2147483647
Unsigned int min: 0 max: 4294967295
Size of long int types is 4 bytes
Signed long min: -2147483648 max: 2147483647
Unsigned long min: 0 max: 4294967295
Size of long long types is 8 bytes
Signed long long min: -9223372036854775808 max: 9223372036854775807
Unsigned long long min: 0 max: 18446744073709551615
Note that int and long are the same size and if you want a 64 bit integer then you need to use long long (or unsigned long long).

What do you want to achieve with

.
CS=30.10 // 30.10
Int_CS=int(CS) // 30
FLOAT_CS = (Int_CS-CS)*100 //-10.00 because 30 - 30.10 = -0.1 and -0.1 * 100 = -10.00

CS is already float, why you want to convert it to int and back to float? If value of int is higher than 255 you have to save it in 2 bytes(highByte and lowByte), float is 32bit(4bytes) value.
I think you have to do like this:
float CS = 30.10;
au16data[0]= (int)(CS*100);//3010.00 > 3010

And for better way use :
float auFloatData[30]; //
...
auFloatData[0]=Current_Value1[0];

Minor correction: Default char is signed in gcc (compiler shipped with arduino). You can pass -funsigned-char compiler flag to have unsigned as default.

@Martynas But i have already tried that.when then it zero at end it print only 301 not 3010. SO it will difficult to recognize .when it turns out 3 digit value.

@AMPS What is the range of CS?

it measure 0~25 A , for understanding i given example above.

What accuracy do you need?

0.5% accuracy. I am considering it for testing. Later i go with other model

@AMPS i edited my answer, see if that is ok for you