body:
I'm currently working on a project that requires to display images on a touchscreen on my arduino. These images are neither stored in arduino nor any memory card. I want to be able to send the images via Bluetooth from an app and display it on the touchscreen. The problem is I couldn't find a good and solid Bluetooth shield or module that provide file transfer via bluetooth from an iOS app to arduino. If you can name a few bluetooh shields or modules that'd be great. In the thread below, someone claimed hc-05 works. Can anyone support that claim? Thanks.
http://forum.arduino.cc/index.php?topic=208306.0

title: Bluetooth shield/module for file transfer?

Answers: 1

body:
I would use an HC-05 (or HC-06 - there seems to be little difference) - You will need to do your own file transfer protocol - for small images, zmodem or xmodem (usual file-over-serial) are probably completely overly complex. You would also need your own app for the phone.

Alternatively, you could use a network (ethernet or wifi) addon on your arduino - I think I read the Arduino Yun has built in ethernet and wifi.http://arduino.cc/en/Tutorial/WebServer has a webserver, this could be adapted to accept uploaded files. You can then use a webbrowser on your phone (or indeed anywhere else!) to send the files. If you want to send from outside your local network, you may need to set up port forwarding on your router (google: port forward) - the port you want to forwards is 80.


body:
With a very simple connection of an LED (which can withstand 5V) to ground and to a pin on my Galileo gen2, I can never output a non-zero voltage from the pin via `analogWrite`, regardless of whether the pin is digital or analog (although PWM digital works)

The LED is in the correct bias and I'm calling `pinMode(pin, OUTPUT)` before attempting to call `analogWrite(pin, 255)` (or any 2nd parameter in-between), even though it's not even necessary.
The LED glows if I call `digitalWrite(pin, HIGH)` on both analog and digital pins, but does not glow at all for `analogWrite(pin, 255)` with the same configuration and pins, nor does it for any 2nd param in [0, 255]. This holds for whether the call is attempted in `loop()` or `setup()`.

The only possible way I can get the LED to receive any power from `analogWrite` is through a digital PWM pin, but I know the other digital pins can still produce square-waves with timers and the analog pins should certainly be able to use PWM.

(So far, I've been to scared of short-circuits to connect the analogWrite output straight into an analog input to read the voltage)

Is there something I don't understand about the underlying board, or am I experiencing some strange malfunction?

Thanks,
Tyson

title: analogWrite never outputs a non-zero voltage

Answers: 3

body: I don't believe Galileo has a D/A converter, which is what it sounds like you're expecting. In the Arduino 'eco-system', analogWrite() sets a PWM duty cycle - that's kinda-sorta somewhat like an analog output, but not really. You could add external circuitry to low-pass filter the PWM and produce some sort of proportional DC but it might be a good trick get it clean enough for whatever you plan to put downstream.

body:
On most boards, the standard implementation of Arduino's `analogWrite()` will only ever produce PWM, and only on a specific set of (digital) pins. These are usually pins 3, 5, 6, 9, 10, and 11, although it's slightly different on some boards.

The only official board which has 'true' analog output is the Due (pins DAC0 and DAC1).

If you want any other behaviour (such as outputting PWM on non-standard pins), you'll either need to modify the Arduino implementation, or directly manipulate the microcontroller's special registers. Note though that modifying the chip's configuration could cause other standard Arduino functions not to work as expected.

body: I am not sure where you are getting your LEDs but the ones I purchase do not survive 5 volts. You need to put a resistor in series with then, something in the 220 to 510 ohm range.  When you get some resistors test your LEDs you may have damaged them as well. A good indication of this if there color if obviously off and or dim. If the timers are set up correctly the digitalwrite will set the PWM value, somewhere from 8 to 16 bits depending on the Arduino and timer used. This PWM output will appear to control the brightness of the LED. It does this by simply turning it on and off at a speed the eyes cannot follow. the longer it is on the brighter it is. Hopefully this will help you get your arms around the circuit.


body:
I'm trying to send a large packet to an Arduino with an ethernet shield on it. I'm using the built-in RX buffer of the W5100 controller to store the data, but I need more memory (at least 16K of buffer space, the W5100 only has 8K of RX buffer space). I have control over the server side of things as I'm writing the server process myself, so I can take solutions on that side.

Is there some hack I can use in the TCP protocol to have the packet broken up?

**Edit:** I'm using the SFML 2.1 network API on the server side.

title: How can I analyse large packets on an Arduino?

Answers: 1

body:
All you need to do is analyse the packet on-the-fly using a state machine.

<http://www.gammon.com.au/statemachine>

You certainly don't need to hold the entire packet at once, however you **do** need room for the information the packet contains.

Say, for example, that the packet, although wordy, contains 4 x 32-bit numbers of interest. All you need memory for is those 4 numbers, plus a minor extra amount for the current data you are processing (eg. the current state, and the current number being assembled).

Conceptually it is like streaming a movie to your PC. The PC doesn't need to hold the whole movie, it just needs to hold the current frame, and a few seconds in advance, just to keep things running smoothly.


body:
I wired my switch just like in the default button program. I know it works because it works fine on other pins, just not pin 18 or 19. What am I doing wrong?

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

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

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

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

      // check if the pushbutton is pressed.
      // if it is, the buttonState is HIGH:
      if (buttonState == HIGH) {
        // turn LED on:
        digitalWrite(ledPin, HIGH);
      }
      else {
        // turn LED off:
        digitalWrite(ledPin, LOW);
      }
    }

title: Why are pin 18 and 19 always HIGH?

Answers: 1

body:
The analog pins function as digital pins number 14 - 19, with 14 being A0 and 19 being A5. I had hooked it up backwards.

    This time we're gonna get funky
    Everybody check your pins
    Check check check check your pins
    Check check check check your pins
![enter image description here][1]

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


body:
I am trying to build a robot, which needs motors to roll around. So I was trying to control two DC motors with H-Bridge that comes with Arduino StarterKit(H-bridge motor driver [L293D]). I used Sketch that looks something like that ![enter image description here][1]

  [1]: https://i.stack.imgur.com/Jh66v.jpg

I did read that Arduino needs separate powering, but i did not use any only USB connection. I connected 5V that comes from arduino to where + pin from battery should have been connected and motors were controlled and working.
However when i tried using 9V battery and connecting it as seen on above picture ,H-bridge did not control mototrs and nothing was working.
There is also another aspect - when robot was touching the surface then wheels did not move aka motors did not rotate and when you picked it up motors accelerated to quite some speed. Also when robot was on the surface and connected via USB, the PC made these USB connecting sounds repeatedly.
I am not sure when RX and TX stopped working. Power LED and L13 LED do work correctly.

Any ideas? Is it Fixable?

title: Arduino UNO does not get recognized by PC(no USB connecting sound), also TX and RX not blinking, neither are lit

Answers: 3

body: You should definitely avoid connecting anything else than 5v to these 5v(!) PINs. The Uno has regulators, but these only work when powered through the power-dc-connector (or USB). You can easily buy a 9v-block to dc-jack cable to connect power to the right point easily.

body:
The "5V" pin takes only regulated 5V input.  Your schematic shows the the board powered here, and you mention 9V battery.  That's not a good idea.

If you have 7V-12V, then you can supply the board via the "Vin" pin.  It passes through the same regulation circuits that the DC jack does.

http://arduino.cc/en/Main/ArduinoBoardUno

> VIN. The input voltage to the Arduino board when it's using an external power source (as opposed to 5 volts from the USB connection or other regulated power source). You can supply voltage through this pin, or, if supplying voltage via the power jack, access it through this pin.

body: May be your ATmega328 IC would have been damaged or ATmega16u or ATmega8u chip was damaged. I also got same few days ago.


body: What is the most accurate proximity sensor for a ping pong ball? I will be using this to calculate 3D positioning of a ping pong ball in flight. I only need to detect the ball within 0-5 feet (basically on one side of ping pong table).

title: What is the most accurate sensor for detecting ping pong ball?

Answers: 2

body:
In the meantime a student has made a really impressive implementation, that might answer your question: [interactive tennis table][1]

  [1]: http://thenextweb.com/gadgets/2016/04/28/interactive-tennis-table-help-step-ping-pong-game/

body:
I've had some good luck with using the Pixy camera system.

http://www.cmucam.org/projects/cmucam5/wiki

You get a maximum of 50 FPS and can detect and locate different objects based on hue. The library function getBlocks() returns the X and Y center location of each of the objects the camera detects. You teach the camera what hues to recognize as blocks, and adjust the detection thresholds. I use mine in monochrome infrared light by adding a visible filter and lens kit from http://irlock.com/


body:
I'm have a [Sleepy Pi][1] and am having extreme difficulties trying to program a wake/sleep cycle. Sleepy Pi is an Arduino board with a RTC. My ultimate goal is for a time-lapse project.

I have the Raspberry Pi programmed and operational to take a picture on boot, my trouble is coming from trying to program the Arduino board to actually do it's job.

I would like the Sleepy Pi to wake at 8am, 9am, 10am, ..., 3pm, 4pm, and 5pm, each for 5 minutes, then go back to sleep. I've been working with the [SleepyPi][2], [Time][3], [TimeAlarms][4], [LowPower][5], and [DS1374RTC][6] libraries in the Arduino IDE. However, I cannot find any examples on how to put everything to sleep until a specific time comes around. Also, in several of my tests, it seems that the clock actually stops when the Sleepy Pi is asleep!

Here is what I've been working with (and this is non-working). It's probably completely wrong.

    #include "SleepyPi.h"
    #include <Time.h>
    #include <TimeAlarms.h>
    #include <LowPower.h>
    #include <DS1374RTC.h>
    #include <Wire.h>

    // Set the status LED pin constant
    const int LED_PIN = 13;

    void setup()
    {
      // Configure "Standard" LED pin
      pinMode(LED_PIN, OUTPUT);
      digitalWrite(LED_PIN,LOW); // Switch off LED

      // Start with the Pi off
      SleepyPi.enablePiPower(false);

      // Set our communication rate
      Serial.begin(9600);

      // Set up our boot times
      Alarm.alarmRepeat(8,0,0, startPiUp);
      Alarm.alarmRepeat(9,0,0, startPiUp);
      Alarm.alarmRepeat(10,0,0, startPiUp);
      Alarm.alarmRepeat(11,0,0, startPiUp);
      Alarm.alarmRepeat(12,0,0, startPiUp);
      Alarm.alarmRepeat(13,0,0, startPiUp);
      Alarm.alarmRepeat(14,0,0, startPiUp);
      Alarm.alarmRepeat(15,0,0, startPiUp);
      Alarm.alarmRepeat(16,0,0, startPiUp);
      Alarm.alarmRepeat(17,0,0, startPiUp);
    }

    void loop()
    {
      // Tick the alarm clock every second
      SleepyPi.enableWakeupAlarm();
      Alarm.delay(1000);

      // Cut Power if we detect Pi not running
      bool pi_running;
      pi_running = SleepyPi.checkPiStatus(true);
      if(pi_running == false){
        SleepyPi.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);
      }

      // Flash the LED
      digitalWrite(LED_PIN,HIGH);
      delay(1000);
      digitalWrite(LED_PIN,LOW);
    }

    // Function to tell the Pi to boot up
    void startPiUp()
    {
      // Turn the Pi on
      SleepyPi.enablePiPower(true);

      // Turn on the LED to signal we're here
      digitalWrite(LED_PIN,HIGH);

      // Keep the Pi on for 5 minutes
      delay(300000);

      // Start a shutdown
      digitalWrite(LED_PIN,LOW);
      SleepyPi.piShutdown(true);
    }

I also cannot find a good way to "debug" things. I've been trying to use the LED flashes as a "I'm here" echo, but have been unsuccessful with this as well.

**NOTE:** I do not have enough reputation on this site yet to create new tags. Someone with over 150, please tag this with [tag:raspberry-pi] and [tag:sleepy-pi]. Thank you.

  [1]: http://spellfoundry.com/products/sleepy-pi/
  [2]: https://github.com/SpellFoundry/SleepyPi
  [3]: http://www.pjrc.com/teensy/td_libs_Time.html
  [4]: http://www.pjrc.com/teensy/td_libs_TimeAlarms.html
  [5]: https://github.com/rocketscream/Low-Power
  [6]: https://github.com/SpellFoundry/DS1374RTC

title: Waking Raspberry Pi on time schedule using Sleepy Pi

Answers: 2

body:
Same probem. Kludgy solution ... but it works

Get the startstopsimple skectch from GitHub.

Set the period to 60 minutes
Set the timeout to whatever makes sense for you

Modify the setup function to loop until the clock says the minute is 59.
something like

    do
    {
       delay (100);
    } while !(minute() == 59);

Then it will go into the loop function. It will be asleep. So it will then do a whole "empty" loop and sync after that, dunno how one gets rid of first the empty loop. But it works .... :-)

body:
I have the same problem and  I just saw that they fixed a bug in a library used by SleepyPi

More specific, the RTC library file [`DS1374RTC.cpp`][1] reads since March: '2015
(which is after the question was asked)

>   Releases
  ========
  V1_0 - 10 Aug 2013 - Initial release
  V1_1 - 11 Mar 2015 - Mod:    Added "ackAlarm" and "ackRTCOSF" functions to aid Alarm use
- Bugfix: **Changed the way the "SetAlarm(tmElements_t   &tm)" was updating the Alarm time.** It wasn't mapping correctly

They also added a new example to wake up the Pi: [`WakePeriodicallySimple.ino`][2]

  [1]: https://github.com/SpellFoundry/DS1374RTC/blob/master/DS1374RTC.cpp
  [2]: https://github.com/SpellFoundry/SleepyPi/blob/master/examples/WakePeriodicallySimple/WakePeriodicallySimple.ino


body: I am new to all of this so anything is helpful.

title: Where can I find beginner tutorials for the Arduino?

Answers: 0


body:
I bought one of [these][1]:

![1Pcs New Sound Detection Sensor Module Voice Sensor for Arduino Best][2]

There are 3 pins on it:

 - 5V
 - GND
 - OUT

My guess is that OUT is an analogue signal that I can measure with my Arduino, am I right?

I am using the "Analogue Output" example code but I just get 5V all the time, it does not seems to change with the sound levels.

Am I doing something wrong? What am I adjusting with the blue square on the board? Should I maybe do that?

  [1]: http://www.ebay.com/itm/171505106187?_trksid=p2059210.m2749.l2649&ssPageName=STRK:MEBIDX:IT
  [2]: https://i.stack.imgur.com/04v2jm.jpg

title: How do I use this sound sensor?

Answers: 1

body:
The wording on this particular eBay item is pretty poor but there are plenty of similar products with better descriptions that are photographically identical... [example][1] that make a little bit more sense.

Anyway, I don't think this gives an analog value output, the LM393 is a comparator, so I think the blue dial sets the 'threshold level' and any sounds over that level cause a logic low. i.e. it compares the audio level and the dial and when one exceeds the other it gives a signal.

The features also say "The output effective signal is low level" which is probably Chinglish for the signal is a logic low, i.e. when the sound is heard it goes to 0V rather than 5V which is what I think you were expecting.

In summary: This device is is more like a Clapper, it detects a loud noise and sends a digital low signal.

Try making a loud noise with the same setup you already have, and if not try adjusting the potentiometer by turning it, but not too far! It probably only turns 180-270º.

  [1]: http://www.ebay.co.uk/itm/1x-Sound-Sensor-Detection-Module-LM393-Electret-Microphone-for-Arduino-/231034416834


body:
I recently read this piece of code and I dont know what is the use of "<<=" in the for loop:

    for (mask = 0x01; mask>0; mask <<= 1) {
        if (data & mask){ // choose bit

This is the entire code:

    //Created August 23 2006
    //Heather Dewey-Hagborg
    //http://www.arduino.cc

    #include <ctype.h>

    #define bit9600Delay 100
    #define halfBit9600Delay 500
    #define bit4800Delay 188
    #define halfBit4800Delay 94

    byte rx = 6;
    byte tx = 7;
    byte SWval;

    void setup() {
      pinMode(rx,INPUT);
      pinMode(tx,OUTPUT);
      digitalWrite(tx,HIGH);
      delay(2);
      digitalWrite(13,HIGH); //turn on debugging LED
      SWprint('h');  //debugging hello
      SWprint('i');
      SWprint(10); //carriage return
    }

    void SWprint(int data)
    {
      byte mask;
      //startbit
      digitalWrite(tx,LOW);
      delayMicroseconds(bit9600Delay);
      for (mask = 0x01; mask>0; mask <<= 1) {
        if (data & mask){ // choose bit
         digitalWrite(tx,HIGH); // send 1
        }
        else{
         digitalWrite(tx,LOW); // send 0
        }
        delayMicroseconds(bit9600Delay);
      }
      //stop bit
      digitalWrite(tx, HIGH);
      delayMicroseconds(bit9600Delay);
    }

    int SWread()
    {
      byte val = 0;
      while (digitalRead(rx));
      //wait for start bit
      if (digitalRead(rx) == LOW) {
        delayMicroseconds(halfBit9600Delay);
        for (int offset = 0; offset < 8; offset++) {
         delayMicroseconds(bit9600Delay);
         val |= digitalRead(rx) << offset;
        }
        //wait for stop bit + extra
        delayMicroseconds(bit9600Delay);
        delayMicroseconds(bit9600Delay);
        return val;
      }
    }

    void loop()
    {
        SWval = SWread();
        SWprint(toupper(SWval));
    }

title: what is the use of "<<=" operator?

Answers: 3

body:
`<<` is the left bit-shift operator. That means it takes the binary contents of a number and moves everything left by a certain number of binary places (1 place in this case). `<<=` simply combines the left bit-shift with an assignment, so it takes the current value of `mask`, shifts it left, and then stores the result back in `mask`.

In this situation, the `mask` variable starts with a value of `1`. The second time round the loop, it will be `10` (binary). Next time, it will be `100`, and so on. Since `mask` is a byte (which is 8 bits), it will go all the way up to `10000000` and then stop. After that, the 1 effectively falls-off the left and `mask` ends up with a value of 0.

The purpose of this in the code you provided is to test each individual bit within the `data` parameter. It basically goes through from least- to most-significant and checks if each bit is 1 or 0. It will then pull an output pin HIGH or LOW (respectively) to match. This allows it to send the contents of the variable digitally to some other device.

Doing low-level binary (aka bit-wise) operations like this is very common in microcontroller programming. If you're not familiar with it then I'd definitely recommend looking up some tutorials online. It opens up a huge range of new possibilities for your projects.

body:
In simpler terms `mask <<= 1` is shorthand for `mask = mask << 1`

In general

    variable operator= operand

is the augmented assignment operator which means

    variable = variable operator operand

body:
As stated in the other answers, the `<<=` operator shifts the byte to the left; however, the number '1'  after it specifies how far to shift it - so, `2 <<= 2` == 8.
Possibly clearer in binary:

`00000001 <<= 1` == `00000010`

`00000010 <<= 1` == `00000100`

`00000001 <<= 2` == `00000100`


body: I want to power xbee s2 module through atmel 328p digital output pin. And I am powering atmel 328p IC using 3.7 li-ion cell 5500 mAh. In sleep mode atmel consume current in micro Amp but xbee consuming around 40 mA. I want to reduce it. I tried xbee in power down mode but its not working for me. Is der any way to switch xbee automatically with as atmel sleep & wake-up. Circuit works properly when I power xbee through 3.7 v li-ion cell but consume power continuously.

title: Xbee power issue

Answers: 2

body:
The best solution would be to determine why your Xbee is not being switched into power down mode.

But, if you wish to turn the Xbee power off using the Arduino then there are many ways of doing this. One method is shown on the diagram below {[**from here**](http://www.microchip.com/forums/m697820.aspx)}. This requires two transistors and three resistors. Almost any small transistors would work. Good choices if buying new components would be BC337 / BC817 for T1 and BC327 / BC807 for T2. The first part number in each pair is a through hole part and the second number is the equivalent surface mount part. If buying these try to get the -40 suffix versions, although in this case any version would work OK.

This circuit was drawn for use with a PIC processor controlling a 12V supply, but the Arduino works equally well controlling a 3.7V LiIon supply. The load is shown as a light bulb - that's where you'd connect the XBee.

![enter image description here][1]

Input low turns 1 off which turns T2 off. To enable/disable the XBee you have to raise / lower the input pin.

  [1]: https://i.stack.imgur.com/Ll7ah.gif

body: I would use a sleep mode, e.g. PIN sleep, in order to reduce the power consumption of the Xbee. At the hardware level, the XBee uses pin 9 as a control pin. This pin can be used to sleep the radio: setting it to 3,3V (“high” or “asserted”) causes the radio to sleep; setting it to 0V (“low” or “deasserted”) wakes the radio up. You can find some useful hints on the following websites http://citizen-sensing.org/2013/08/xbee-sleeping/ or https://www.digi.com/wiki/developer/index.php/Designing_a_Sleeping_XBee_Sensor  or here http://www.johnhenryshammer.com/WOW2/pagesHowTo/xbeeSeries1.php#index.


body:
Without asking an open-ended question, i wish to find the best way (resourcefulness) to execute methods from an arduino based on time.

in a nutshell, every 10 minutes i want functionA() to be called & every 30 minutes, functionB(). At this point i'm unable to specifiy whether a method would need to be called at a less frequent rate, however i wish to assume that one may.

My 2 ideas so far:

 - encapsulate the functions a & b inside the NTP client, and execute based on the minutes in an hour

<b>or</b>

 - use delay() or even the milli() counter with functions a & b below inside the loop.

My main worry of the 2nd option is that the arduino handles time keeping itself, in a long run (lets say 1 year), the arduino will end up with no memory left. Whats is the consensus with this?

Board wise, to be run on Uno & Mega.

title: Time based scheduling, NTP vs delay()

Answers: 3

body:
memory used by delay() and milli() (if any) will be recycled every time you call it, so it does not add up. You should be aware that milli rolls over (resets back to 0) after approximately 50 days - see http://arduino.cc/en/Reference/Millis - you will need to keep track of how many times it has overflowed, and include that in your calculations.

delay will only be useful if you do NOTHING AT ALL during that time - if you want to do other stuff in that space, you should use milli(). Also, if you delay (without using milli()), your events will drift by the time it takes to run the code. delay() and milli() will also only be as accurate as the crystal on your arduino - it should be no more than 20 parts per million; this comes to 10 minutes per year. This may or may not be a problem.

NTP will use a lot more resources, and has to be polled. It is also potentially less reliable (i.e. NTP may be down for short periods).

If you need accurate timing, the best solution would be to use delay() to pass the time (approximately), milli() to keep the time, and adjust for drift with NTP.

body:
Connect a battery backed up Real-Time clock to your arduino and use that to keep track of the time.

Basically the same idea as NTP but minimal hardware is required and you can get an RTC with the long term accuracy you need.

body:
Both NTP and milli() waste a lot of processing as it keeps the Arduino busy checking if the time is right.

Your best bet is to use the Arduino timer. Set the timer to interrupt every 10 minutes. If you don't need to do anything aside from functions A and B, you can let your Arduino sleep and keep power draw to a minimum.

    // Example code
    void funcA(){
        // do stuff
    }
    void funcB(){
        // do stuff
    }

    void setup() {

        // initialize Timer1
        cli();          // disable global interrupts
        TCCR1A = 0;     // clear TCCR1A
        TCCR1B = 0;     // same for TCCR1B

        // set compare match register to desired timer count:
        // 15624*1024/16000000 = 1sec at 16MHz
        OCR1A = 15624;
        // turn on CTC mode:
        TCCR1B |= (1 << WGM12);
        // use 1/1024 the speed of the clock:
        TCCR1B |= (1 << CS10);
        TCCR1B |= (1 << CS12);
        // enable timer compare interrupt:
        TIMSK1 |= (1 << OCIE1A);
        // enable global interrupts:
        sei();
    }

    ISR(TIM1_COMPA_vect)
    // Your task manager here
    // This function decides when to execute the functions A and B
    {
        static t1= 0;
        static t2= 0;

        // increment your counter flags
        t1++;
        t2++;

        if (t1==10) {//runs function every 10 sec
            funcA();
            t1=0;
        }
        if (t2==30) {//runs function every 30 sec
            funcB();
            t2=0;
        }
    }

    void loop(){

        // do stuff or sleep for even more power saving
    }

Hope this helps.


body:
I'm trying to get students to experiment with Arduino. However, due to a lack of boards, two teams of students will collaborate on each board. They will push their own code (independent from each other) and use half the pins.

The "hardware" part isn't really a concern: students will push their sketches on a server that uploads them on the board, or something like that.

What I'm worried about is the software part. **How can I allow two sketches to run on the same board**, and **allow the user to upload sketches without resetting the board**?

----

As of my understanding, using the flash memory isn't an option, because the board must be reset before it can be written.

My first idea was to compile the students' C code into custom-made "assembly", and then push the assembly code to the board, which stores it into RAM and interprets it. However, my biggest problem would be implementing functions, I don't really have a clue of how I could do that. While common C functions could just be encoded in a fashion like `FUNC printf STRING %s VAR a` for `printf("%s", a)`, I don't know how to encode user-defined functions. Besides, I don't even think the RAM is sufficient for running the client, storing two small programs, and running them.

Then, I thought about running the C code on the computer, but replacing `digitalWrite` with appropriate signals to the board. However, I'm worried about the performance of this, mostly when dealing with "high" speeds - say, using a custom-made library to print text on a LCD driver.

title: How can I run multiple programs on an Arduino?

Answers: 5

body:
There is a solution. It requires some programming discipline from your students, but it is feasible.

1) Make sure each group uses different variable and function naming conventions (one starts all variable and functions with `a_` and the other group with `b_`). These functions will be written in separate include files.

2) In the `setup()` and in the `loop()` functions, you will call either `a_setup()` or `b_setup()`, and either `a_loop()` or `b_loop()`. Each of the group setup and loop functions will call their functions and use their variables as the groups want to, but they are not allowed to call variables/functions from the other group. Other resources can also be allocated by you in advance for each team.

3) During the `setup()` function, start by reading a specific input that you will either connect to GND or to 5V. Use the result of this reading to execute either one version of the software, or the other.

This is not elegant, but it gets two program into each Arduino.

body:
> How can I allow two sketches to run on the same board, and allow the user to upload sketches without resetting the board?

This is "easily" dealt with as long as you can enforce certain minimum disciplines.

Students must only use assigned pins.

Identifiers (functions, variables ...) defined by a group must always be unique to that group. This can be as simple as eg always starting with a group specific symbol or eg one group NEVER using a z in names and the other ALWAYS using Z etc. Annoying but easy.

Loop() contains calls to two non-terminating functions eg Group1() and Group2()
All code for Group1 is in Group1() and ....

One digital pin is assigned for Giulio's use.
When GiuliosPin is low the system executes Group1() - and never exits it until restarted.
When GiuliosPin is high the system executes Group2() - and never exits it until restarted.

I uses a system very close to the Group1() / Group2() selection for my own purposes to allow multiple sketches to be compiled at once - but I use a constant which is set  as I compile to choose which to run. My concern is the ability to test multiple code fragments.

____________________

Added:

After reading Mac's similar answer I see I missed mentioning Setup().
Code from both users can be merged into the same Setup() as the identifiers are unique.
Or the Setup() function for each Group can be carried out inside their unique Groupx() function with a "run once" function at the start of their code. This is a matter of programming discipline and not in any way hard per se.

body:
In addition to the other answers, I have a few ideas:

1.) Instead of doing variable prefixes, have them wrap all of their code inside a namespace! Please note that you can't wrap "setup" or "loop" in that namespace. Example

    setup() {
      if(conditionIsTrue) {
        aGroup::setup();
      } else {
        bGroup::setup();
      }
    }

    loop() {
      if(conditionIsTrue) {
        aGroup::loop();
      } else {
        bGroup::loop();
      }
    }

    namespace aGroup {
    setup() {
      // Code
    }

    loop() {
      // Code
    }
    }

    namespace bGroup {
    setup() {
      // Code
    }

    loop() {
      // Code
    }
    }

2.)

Please note you'll have issues with a student tries to access an analog pin and doesn't prefix it with `A`. For example, if I wanted analog pin 5, I should do `analogRead(A5);`, ***not*** `analogRead(5);`. That could cause some major issues.

body:
There is no native multitasking on an Arduino. A few solutions have been suggested above, all of which depend on cooperative multitasking - each half has to play fair.

An alternative may be this:

Buy some AtTiny chips - e.g. AtTiny 24a; they are about $2-3 each. Buy some VeroBoard. Solder the AtTiny on to the board, so each verboard strip has 2 pins on it (not the other way, where each veroboard strip has half of the pins on it). Solder on some pins, cut the track between the pairs of pins, and cut the board to size. You should be able to get a working board, with 12 usable pins per board, and you'll be paying less than $5 per board in your local currency. Buy a USBISP, and hook up the pins, whenever you need to program them - I suggest using the FreeTronics programmer, like this one here: http://www.jaycar.com.au/productView.asp?ID=XC4237 - you can solder 2 pins for the "slow clock" option - you'll need this. Optionally, you could make an adapter board which plugs into all of the relevant pins in one go, to program it. You should only need one of these. To figure out which wires to connect where, compare the top diagram on http://www.dz863.com/datasheet-8310956563-ATTINY24A-SSU_8-bit-Microcontroller-With-2k-4k-Bytes-In-system-Programmable-Flash/ with https://www.olimex.com/Products/AVR/Programmers/AVR-ICSP/resources/AVR-ICSP.gif

You can power them with AA batteries or an external power supply - you could easily make one power supply that runs many boards. Check out the spec sheet for the voltage required - it varies, depending on the clock speed (default clock speed as described is 1 MHz, google "avr fuses" for how to set them to e.g. 8 MHz at no extra cost).

body:
A little late, but I used a potentiometer as a switch to determine which "sketch" to run; in this case swapping LEDs on/off. I assume it can be applied to this instance, the students just have to share/divide pins and declare variables together at the top with comments. (I'm new at this, but I think a shift register (75HC595) could be used if you run out of pins). Thoughts?

EDIT: Potentiometers give a value of 0-1023. I split that up into 2, 3, and 4 separate sketches with no problems. You just have to change the IF/ELSEIFs to reflect how many sketches you want to run (512 for 2, 341 for 3, ~256 for 4, etc).

    int sensorPin = 0;
    int sensorValue = 0;
    int ledPin1 = 4;
    int ledPin2 = 8;

    void setup() {

      pinMode(ledPin1, OUTPUT);
      pinMode(ledPin2, OUTPUT);
    }

    void loop() {

      sensorValue = analogRead(sensorPin);

      if (sensorValue < 512)
    {
        digitalWrite(ledPin1,HIGH);
        digitalWrite(ledPin2,LOW);
    }

      else
    {
        digitalWrite(ledPin2,HIGH);
        digitalWrite(ledPin1,LOW);
    }
    }


body:
I have the Arduino board connected to a USB port of my machine. But I cannot find it under /dev/ directory in my Ubuntu. Does anyone know how to deal with this issue? By the way, "lsusb"'s output proves that it has been recognized. Here is the output of this command:

    Bus 002 Device 002: ID 8087:8000 Intel Corp.
    Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
    Bus 001 Device 002: ID 8087:8008 Intel Corp.
    Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
    Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
    Bus 003 Device 007: ID 413c:2105 Dell Computer Corp. Model L100 Keyboard
    Bus 003 Device 013: ID 2341:0043 Arduino SA Uno R3 (CDC ACM)
    Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Here is the output of ls -l /dev/ttyACM*

    ls: cannot access /dev/ttyACM*: No such file or directory

and the dmesg output when disconnect and reconnect the device:

    [1653809.002715] usb 3-11: USB disconnect, device number 13
    [1653832.188835] usb 3-11: new full-speed USB device number 14 using xhci_hcd
    [1653832.211392] usb 3-11: New USB device found, idVendor=2341, idProduct=0043
    [1653832.218400] usb 3-11: New USB device strings: Mfr=1, Product=2, SerialNumber=220
    [1653832.226003] usb 3-11: Manufacturer: Arduino (www.arduino.cc)
    [1653832.231859] usb 3-11: SerialNumber: 85235353137351708191
    [1653832.237468] usb 3-11: ep 0x82 - rounding interval to 1024 microframes, ep desc says 2040 microframes

title: Cannot find Arduino under /dev Directory

Answers: 1

body:
Note that lsusb does not guarantee the drives are loaded (See https://superuser.com/questions/165733/will-lsusb-and-lspci-list-devices-for-which-the-system-has-no-drivers)

Per the https://stackoverflow.com/a/14586884/1653571 answer, try an 'lsmod' and see whether you have a 'cdc_acm' module loaded.


body:
I bought a SainSmart Arduino Mega 2560. I uploaded a small sketch to it, and it uploaded fine. When I upload a larger sketch though, I get this error:

    verification error, first mismatch at byte 0x3895
             0xdf != 0x44
So obviously there's nothing wrong with my bootloader because I can upload smaller files. Why is this happening?

title: verification error, first mismatch at byte 0x3895 0xdf != 0x44?

Answers: 2

body:
If your sketch contains !!! in it, that can cause some versions of the bootloader to drop into interactive mode, eg.

    Serial.println ("Rocket firing!!!");

Also there can be problems with 0xFF bytes in your code causing the bootloader to incorrectly assume that that page of memory was erased, when it was not.

I have a bootloader-uploader sketch at: [Atmega bootloader programmer](http://www.gammon.com.au/bootloader)

You need a second board to use it (eg. a Uno) - the bootloader for the Mega2560 is a reasonably up-to-date one. I haven't actually tested it with the Sainsmart version of the Mega, but I presume that internally that part is the same.

body:
I believe I have finally understood this error today, and would like someone to verify or refute.

In "avrdude.conf" there is defined for each processor and for each memory type a minimum duration and a maximum duration that the programmer will repeat trying to write each byte. These have values of "min_write_delay = 4500" and "max_write_delay = 4500" (no idea what the units are).

After increasing the max_write_delay to "max_write_delay = 16000" (arbitrary increase but keeping it less than a 16 bit signed integer to avoid buffer overflow risks), for all memory types (but I would presume that only "flash" memory needs the parameter to be altered) my Arduino takes an extra 30 seconds to program, but no more verification errors.


body:
I wanted to know if the reference voltage for the `digitalRead()` function could be set to a particular voltage, either with an external reference or internally.

In the Arduino reference under the constants heading they have mentioned that they use 3V as reference for the boards I'm using (an Arduino Uno R3). But I want to change it to be a little lower.

Is it possible and if so how?

title: Set Arduino digitalRead reference voltage

Answers: 2

body: for a 5 volt Arduino anything over 2.7V will be considered as a digital HIGH whereas anything below 0.4V will be a digital LOW.

body:
You could try not `digitalRead`, but `analogReadVoltage`. [Analog Read Voltage][1]

From Arduino examples:

    /*
      ReadAnalogVoltage
      Reads an analog input on pin 0, converts it to voltage, and prints the result to the serial monitor.
      Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.

     This example code is in the public domain.
     */

    // the setup routine runs once when you press reset:
    void setup() {
      // initialize serial communication at 9600 bits per second:
      Serial.begin(9600);
    }

    // the loop routine runs over and over again forever:
    void loop() {
      // read the input on analog pin 0:
      int sensorValue = analogRead(A0);
      // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
      float voltage = sensorValue * (5.0 / 1023.0);
      // print out the value you read:
      Serial.println(voltage);
    }

  [1]: http://arduino.cc/en/Tutorial/ReadAnalogVoltage


body:
i would like to generate Chirp Signal (Frequency Sweep) using Arduino. i have searched a lot in internet but didn't find anything.

Basically, any parameters is also ok. But the concept is what i am searching for.
The signal will be sent to the DAC of the Arduino board.

Edit
I would like to generate sine wave signal from 3kHz up to 100kHz sweep frequency with amplitude peak to peak 1.5 volt.

thanks for your support.

title: How to generate Chirp Signal using Arduino

Answers: 3

body:
Recommend to use a VCO PLL as external hardware device to get the wanted variable-frequency signal. The DAC output from Arduino can control the voltage to external VCO PLL module. Here is the link for an app note for VCO PLL from Vectron.

http://www.vectron.com/products/vcxo/vcxo.pdf

Hope it helps.

body:
If you're ok with starting with square wave signals, this can be done on an Arduino.
You need to do the following:

 1. Configure a 16-bit Timer to **CTC** mode
 2. Select the right prescaling
 3. Add a RC low pass filter to the output and voltage divider

Configure a 16-bit Timer to **CTC** mode
-----------------
Assuming I'm using **Timer 1** and **OCR1A**:

    TCCR1A |= (1<<COM1A0); // Toggle OC1A on match
    TCCR1B |= (1<<WGM12); // Clear to Compare mode
    TCCR1B |= (1<<CS10); // No prescale

Select the right prescaling
-----------------
In case you're wondering, prescales are used when the MCU clock is much faster than the output you desire.
Without prescaling, the highest frequency is 16MHz/2 = 8MHz, and the lowest frequency would be 8MHz / 2^16 = 122Hz . Which covers the range of frequencies that we want.

Setting OCR1A value to 80 gives you a frequency of 100kHz
Setting OCR1A value to 2667 gives you a frequency of 2.9996kHz

You can then control the chirp like so:

    // Linear rise in wave period
    int x = 10;
    for (int x=80; x < 2668; ++x){
      OCR1A = x;
      delay(10); // 10ms delay
    }

Add a RC low pass filter to the output and voltage divider
-----------------
Making the perfect sine waves may be too troublesome, so we'll resort to the poor man's sine wave.

Here's the [poor man's implementation][1] by TI (still require quite a few parts.)

Personally, I'm cheap so I'd go for the [RLC approach][2]. ;-)

  [1]: http://www.ti.com/lit/an/sbfa003/sbfa003.pdf
  [2]: http://www.wenzel.com/documents/waveform.html

body:
Since you mentioned SINE wave, I think you're seeking a SWEEP signal.  A chirp is a much more complex sound.

To get a sine wave sweep, you probably want a sine function that doesn't use up most of the Arduino executable space.

You can use one of the compact sin(theta) functions that leverage a simple table of values. Just pull the code you need from the cordic.c here: https://people.sc.fsu.edu/~jburkardt/c_src/cordic/cordic.html. C runs in Arduino sketches almost out of the box. You may or may not need some things from the cordic.h. That's why I said "almost". The cordic_prb.c test file has a function test002() that shows you how to call the sine function.

Letting theta = t * (t + k), you will get your sweep, with your instantaneous frequency, f = 2 * pi * (t + k).  You will need to calculate the correct k and set t_max to end your loop.  This can be obtained from the above formula and your f_min of 3kHz and f_max of 100kHz.

You can use a linear translation to get the sample in the range of values that you want: s = s_center + s_peak * sin(theta) / 2, but you will need to calculate your s_ave and s_peak from your center voltage, V_center, and your peak to peak voltage, V_peak.  So there are two translations.  This second one depends on the Voltage range of your Arduino board DAC.

Record your sample and voltage range for the board and then Work backward from Voltage range to V_center and V_peak to s_center and s_peak to your two coefficients to multiply and add to your sin(theta) result.

It's just a little algebra and some integration of some code, and you've got your SWEEP generator.

Also remember that boards like the Uno and Mega do not have a real D-to-A converter, so they will only give you a rectangular wave that has digital noise over the primary harmonic that approximates your sweep.  Use the Due to avoid lots of digital noise. That's the down side of the pulse width modulation of the lower end Arduino chips.

Either way, you may want to attenuate higher frequencies from any type of D-to-A conversion with a simple passive (RC) or active (op amp) low pass filter.


body:
I have worked on [SPI][1] devices connected with an Arduino one at a time. How do I work with two different SPI devices at the same time?

  [1]: http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus

title: How to access multiple SPI interfaces on Arduino

Answers: 1

body:
Assuming you just want to connect two SPI slave devices to the SPI bus and use them in a mutually exclusive way under software control, with the Arduino as the master, then you just need to make sure you use a different pin for the slave select (SS) on each SPI device.

When you want to talk to one slave, you hold its SS low and drive the other high. Do the opposite to talk to the other slave.

There are some devils in the detail using multiple slaves, and [these are explained in more depth here](https://learn.sparkfun.com/tutorials/serial-peripheral-interface-spi), but in general, it's quite common and OK to use more than one SPI device as a slave.

[This blog post](http://www.dorkbotpdx.org/blog/paul/better_spi_bus_design_in_3_steps) will give you more information and is a good place to start reading.


body:
I am wondering if anybody has ideas for developing an Arduino-based system that would use RFID to log occurrences when two people are in close proximity to each other (e.g., <= 1 meter).  Ideally, I would like to construct something that would operate in a manner very similar to the OpenBeacon system -- and, preferably, the events/data would be transmitted via wi-fi in real time.

My ideas are as follows, so any feedback or alternative solutions would be greatly appreciated.  (Please keep in mind that I am not an engineer!)

I am thinking of using a wi-fi enable microprocessor (e.g., Arduino Yun) that would serve as the reader or detection system.  For beta-testing, this device could be set in an enclosed case and attached to a belt.  I presume it would require a fairly robust battery supply.  The other person would be wearing an RFID tag that has a range of <= 1 meter and would log the event.  Ideally, a reading would take place roughly every 30 seconds, and the captured event would be transmitted over wi-fi.

Here are a few other things to keep in mind:

1.  The people using the hardware should not have to do anything other than simply wear the constructed devices.

2.  The reader itself should be as small as possible.

3.  My ultimate goal is the data logging of the proximal events.

I am certainly open to other technologies, as my ultimate goal is simply the proximity detection with data logging (preferably via wi-fi).

Thanks in advance!
Brian

title: RFID system for proximity detection with data logging

Answers: 2

body:
This is a cheapo 125khz reader from Seeed Studio (Shenzhen):
http://www.seeedstudio.com/wiki/index.php?title=Electronic_brick_-_125Khz_RFID_Card_Reader

The range on it is very limited and I'm not suggesting you buy that specific one. Instead, just notice the pinout, +,-,TX,RX. You will find many, many readers with that same pinout. When a tag is detected, the reader blindly transmits the ID via UART (serial). You will also find many WiFi modules with similar TX/RX pins.

In your situation, the Arduino is actually wasteful since it's only purpose will be to mirror the reader's data from it's RX to it's TX. It's better to cut out the middle-man and just connect the (voltage-compatible) reader directly to the WiFi module to save power.

Many wireless modules are capable of automatically going low-power when there is nothing to do. Part of the receiver circuit will activate for transmitting, but since you are only transmitting sporadically from the belts, neither the receiver or transmitter needs to be powered constantly. I think you will be pleasantly surprised by the battery life.

body:
Consider using two basic XXMhz transceivers:

    -Master loops through used ID's and transmits them one at a time.
    -If a belt receives an ID other than it's own, it remains quiet.
    -If a belt receives it's own ID, it transmits "Marco" (quietly) to the other belts.
    -For a receiver to hear the very quiet signal, it will need to be very close.
    -The RSSI signal can be monitored for signal strength to determine close(enough) proximity.
    -If sufficient proximity is detected, the event is reported to the Master.
    -If it receives no response, it informs the Master.
    -Master proceeds to the next ID.

In this setup, you only need to provide networking (WiFi/Ethernet) to the master. (cheaper)

So that each belt can identify the others, "Marco" could be the transmitter's ID, but you'll need to add some sort of "protocol" so the belts know if the ID they hear is from the Master or another belt.

If ID is only 7 bits, the "protocol" could be as simple as a bitmask:

    Server = Send(ID &  (1 << 7)); //1XXXXXXX
      Belt = Send(ID & ~(1 << 7)); //0XXXXXXX

Belts only reply to their ID if MSB is 1

This example has excessive range for your purpose (250m); these radios will be screaming at each other and the RSSI signal is unlikely to provide meaningful data.
http://www.seeedstudio.com/depot/nRF24L01Module-p-1394.html

    Using RFID, you are wanting (very)long range from an (intentionally) short-ranged system.
    Using ISM, you are wanting (very)short range from an (intentionally) long-ranged system.

Neither is 100%, but both should work.


body:
Building a 9x9 LED matrix and facing following 2 problems in Arduino code,

The current code displays 2 images (using byte arrays and then using bitRead) one by one, each for a certain duration of seconds. Persistence of vision is obtained by a delay of 300ms. There is a subroutine called upon in the main loop function with arguments of desired byte array and duration. I want to control the images by using 2 push buttons (push button1 and it displays 1st image until button2 is pressed, push button2 and second image is displayed until button1 is pressed). But the scanning algorithm exits the scan routine upon completion of the given input duration and restarts the routine with new argument (byte array of image2). I WANT THE IMAGE TO BE RETAINED ON THE MATRIX UNTIL BUTTON IS PRESSED. Can't figure out how to accomplish this.

If i nest the routine in a DO WHILE loop, then my problem is that how will the buttons be read from the main loop? Because I believe as long as the subroutine is being executed, main loop will be halted. (or I am totally wrong in this assumption?)

Reference code which I intend to manipulate. (Here its for an 8x8 Matrix. Thats not an issue)

    byte bigHeart[] = {
        B01100110,
        B11111111,
        B11111111,
        B11111111,
        B01111110,
        B00111100,
        B00011000,
        B00000000};

    byte smallHeart[] = {
        B00000000,
        B00000000,
        B00010100,
        B00111110,
        B00111110,
        B00011100,
        B00001000,
        B00000000};

    const int columnPins[] = { 2, 3, 4, 5, 6, 7, 8, 9};
    const int rowPins[] = { 10,11,12,15,16,17,18,19};

    void setup() {
        for (int i = 0; i < 8; i++)
        {
            pinMode(rowPins[i], OUTPUT); // make all the LED pins outputs
            pinMode(columnPins[i], OUTPUT);
            digitalWrite(columnPins[i], HIGH); // disconnect column pins from Ground
        }
    }

    void loop() {
        int pulseDelay = 800 ; // milliseconds to wait between beats
        show(smallHeart, 80); // show the small heart image for 100 ms
        show(bigHeart, 160); // followed by the big heart for 200ms
        delay(pulseDelay); // show nothing between beats
    }

    // routine to show a frame of an image stored in the array pointed to by the
    // image parameter.
    // the frame is repeated for the given duration in milliseconds
    void show( byte * image, unsigned long duration)
    {
        unsigned long start = millis(); // begin timing the animation
        while (start + duration > millis()) // loop until the duration period has passed
        {
            for(int row = 0; row < 8; row++)
            {
                digitalWrite(rowPins[row], HIGH); // connect row to +5 volts
                for(int column = 0; column < 8; column++)
                {
                    boolean pixel = bitRead(image[row],column);
                    if(pixel == 1)
                    {
                        digitalWrite(columnPins[column], LOW); // connect column to Gnd
                    }
                    delayMicroseconds(300); // a small delay for each LED
                    digitalWrite(columnPins[column], HIGH); // disconnect column from Gnd
                }

                digitalWrite(rowPins[row], LOW); // disconnect LEDs
            }
        }
    }

title: Controlling image display on LED matrix by buttons

Answers: 1

body:
OK. Figured out a solution which is working for me. Upon reading a forum on Arduino.cc. That stated a nice analogy to handle this issue.

You have something to heat up on stove while also waiting for an important email which you have to respond to immediately. (You only have a PC in the farthest corner of house at which you have to monitor your outlook :D) How will you do both tasks simultaneously? Run the stove for 10seconds, go to PC to check email, return to stove, run it again for 10 seconds, then again go to PC to check email. Do this until you get the email or your food gets hot enough.

To implement this in our program. I read the states of 2 buttons at start of the main loop. Store their values in 2 variables. Then check the values to check if some button is pressed. if value A is 1 and B is 0, call function A, if A is 0 and B is 1 call function B. The called function comprises of the scan routine. So when called, it performs 1 scan and comes back to the main loop. If no button was pressed meanwhile, the variables have same values, so the same function is called again and it performs the 2nd scan. if a button was pressed meanwhile, then 2nd function is called instead of the 1st one. The speed of all this is enough so that the user does not experience any delays, neither Arduino misses a button pressed while executing the scan.

The LEDs started to flicker when I implemented this code. So I further reduced the delay in the scan routine (time for which each LED is lit before turning it off and lighting the next one) from 300 microsecond to 100 and all went fine. My matrix of 64 LEDs is working fine however I assume that if matrix goes beyond some 100 LEDs then problems like delay or flickering or reduced brightness may arise.

Here is the complete code

    byte img1[] = {
        B01100110,
        B11111111,
        B11111111,
        B11111111,
        B01111110,
        B00111100,
        B00011000,
        B00000000
    };

    byte img2[] = {
        B00000000,
        B01100110,
        B01100110,
        B00000000,
        B00011000,
        B10000001,
        B01000010,
        B00111100
    };

    const int rowPins[] = {13,12,11,10,9,8,7,6};
    const int columnPins[] = {5,4,3,2,14,15,16,17};

    const int but1 = 18;
    const int but2 = 19;

    int but1State = 0;
    int but2State = 0;
    int but1Now;
    int but2Now;

    int value1;
    int value2;

    void setup() {

        for (int i = 0; i<8; i++){
            pinMode(rowPins[i], OUTPUT);
            pinMode(columnPins[i], OUTPUT);
            digitalWrite(columnPins[i], HIGH);
        }

        pinMode(but1, INPUT);
        pinMode(but2, INPUT);

        but1State = digitalRead(but1);
        but2State = digitalRead(but2);
    }

    void loop() {

        but1Now = digitalRead(but1);
        delay(5);
        int but1Now1 = digitalRead(but1);

        if(but1Now == but1Now1)
        {
            if(but1Now != but1State)
            {
                value1 = 1;
                value2 = 0;
                //show(img2);
            }

            but1State = but1Now;
        }

        but2Now = digitalRead(but2);
        delay(5);
        int but2Now1 = digitalRead(but2);

        if(but2Now == but2Now1)
        {
            if(but2Now != but2State)
            {
                value1 = 0;
                value2 = 1;
                //show(img2);
            }

            but2State = but2Now;
        }

        if(value1 == 1)
        {
            show(img1);
        }

        if(value2 == 1)
        {
            show(img2);
        }
    }

    void show(byte*image) {

        for(int row = 0; row<8; row++)
        {
            digitalWrite(rowPins[row], HIGH);

            for(int col=0; col<8; col++)
            {
                boolean pixel = bitRead(image[row],col);

                if(pixel == 1)
                {
                    digitalWrite(columnPins[col], LOW);
                }

                delayMicroseconds(150);
                digitalWrite(columnPins[col], HIGH);
            }

            digitalWrite(rowPins[row], LOW);
        }
    }


body:
I have a prototyping shield for an Arduino Uno. I accidentally plugged the shield into my arduino so that the pins were all "off by one". I didn't think this was possible, but it turns out that the extra pin just slips between the gaps in the pin headers:

![enter image description here][1]

I powered it on not realising. The arduino didn't show any LEDs, so I powered it down, saw my mistake, and plugged it all in again.

Now though A0-A5 are all reading high values (~900-1000 when I do `analogRead(A0)`), even when I have pulldown resistors on them, and they still read like that when I unplug my shield all together.

The digital writes all work perfectly.

I'm thinking that I've broken the Arduino. Is that possible, or could it be something else?

  [1]: https://i.stack.imgur.com/gfEkK.jpg

title: Plugged in shield off by one, now all analogues read high

Answers: 1

body:
There is not (yet) enough information to be certain, but it seems likely that you have damaged the Arduino.

If damage has occurred it's more likely to have been caused by what happened on the other side of the board, where pins carry power supply voltages. You do not say what your power source is or where it is connected (USB, 5V in, Vin, ...) but I'd guesstimate that the connection of UNO 5V to Shield 3V3 allowed back feed into the UNO by any of a number of possible paths. UNO Vin connects to shield ground and a second UNO ground connects to a second UNO ground - so if the UNO was powered via Vin you'd expect the power supply to have been shorted. This might damage some power supplies but usually not.

Can you please advise what voltage was connected and to what pin. And do shield pins all offset by 1 on the other side, as I've shown?

![enter image description here][1]

  [1]: https://i.stack.imgur.com/aqz5m.jpg


body:
I came across something strange while reading the datasheet for the microcontroller in the Arduino Uno board.

It is the (8) note in pg.296-297 of [this datasheet][1]: what does WORDS mean in that context?

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

title: WORDS in ATmega328 datasheet note

Answers: 2

body:
**See jwpat7's answer.**
My answer is correct re address word BUT
his points out that "Words" are being addressed and not bytes.  While my answer is not wrong, his is more likely to be what the writer meant in his excessively cryptic footnote.

A Byte is most usually used to refer to an 8 bit quantity.

A "word" is usually used to refer to a multi-Byte variable with the length depending on both processor type and context.

In this case, on page 296, table 28-19 information is given on the format of 4 byte Instructions. These instructions are NOT referred to as Words although in some other contexts they might be.

However,  the "Write Program memory page" instruction contains the address of a memory page. This address is made up of a 16 bit field comprised of 2 Bytes - an MSB and an LSB.
The notation "Words" is shown against the MSB and the LSB to denote (not very clearly) that a single 16 bit "**Address Word**"is formed by the MSB + LSB combination.

![enter image description here][2]

  [1]: https://i.stack.imgur.com/kKy4U.jpg
  [2]: https://i.stack.imgur.com/byfyD.jpg

body:
The notation is being used to indicate that the 16-bit address (as formed by the central bytes of a Write Program Memory Page instruction) is the address of a program-memory *word*, rather than a  program-memory *byte*.

The size of program memory is specified in bytes, but it often is addressed as words.  For example, the PC (program counter) register contains word addresses.

For some instructions, when the Z register is used to address program memory, it contains a word number and a byte selector:
> The Z-register in the Register File is used to access the Program memory. This 16 bits register pair is used as a 16 bits pointer to the Program memory. The 15 most significant bits selects the word address in Program memory. Because of this, the word address is multiplied by two before it is put in the Z-register. ... The least significant bit of the Z Address Register selects either Low byte (0) or High
byte(1) of the Program memory word. — [AVR108: Setup and Use of the LPM Instruction](http://www.atmel.com/Images/doc1233.pdf), page 1

*Note:* Some of the low bits of the word address in a “Write Program memory page” serial programming instruction are treated as don't-cares.  The number of don't-care bits depends on flash page size, which in Atmel AVR devices is 32, 64 or 128 words, depending on device series.

For example (as shown in Table 129 on page 304 of [doc2467.pdf](http://www.atmel.com/images/doc2467.pdf)) the ATmega128 with 128-word (256-byte) flash pages has seven don't-care bits in the low byte of the address.

    Table 129. SPI Serial Programming Instruction Set
                     -----------Instruction Format----------
     Instruction       Byte 1    Byte 2    Byte 3    Byte 4    Operation

    Write Program    0100 1100 aaaa aaaa bxxx xxxx xxxx xxxx
    Memory Page                                              Write Program Memory
                                                             Page at address a:b.


body:
I got a bit confused by Sparkfun's [hookup guide](https://learn.sparkfun.com/tutorials/lsm9ds0-hookup-guide) for [this 9DoF breakout](https://www.sparkfun.com/products/12636) module.

It says the VDD-in on the breakout *"should [get voltage] regulated between 2.4V and 3.6V"*, yet in their example they do not hook it up to the Arduino's 3.3V pin, but instead they use the 5V and a bi-directional logic level converter.

Do I need to use the logic level converter, or can I just hook the module up to the 3.3V pin of my Arduino Uno without damaging the breakout module?

title: Connecting a LSM9DS0 9DoF module to Arduino Uno

Answers: 1

body:
I might be missing the part of the hookup guide you're looking at but I can't see it being hooked up to 5V.

In the "Simple Hardware Hookup (I2C)" section they show two possiblilities a 5V Arduino hooked up via a logic level converter and a 3.3V Arduino hooked up directly. The logic level converter will need a 5V & 3.3V connection from the Arduino, but not the IMU.


body:
What's the best/easiest software to make a PC-Arduino interface? Ideally, I need to create a .exe that shows up a simple graphic interface, where the user can display data acquired from sensors connected to the Arduino (eg. Voltage, current etc.) and from there he should be able to control Arduino outputs through graphical buttons/switches.

To say that I am not a programmer, so if there's some sort of 'graphical coding' or 'non coding' software to make such things it'd be great!

Thanks for your help!!!

UPDATE:

Image of how the user interface should look like:

![Image of how the user interface should look like][1]

  [1]: https://i.stack.imgur.com/zwsC9.jpg

title: Make a PC graphical interface for Arduino - Any easy software?

Answers: 3

body:
Almost impossible to answer really. Questions with "best" are always going to yield opinions which probably won't apply to your situation. For example, I would do a C# desktop application because that's what I do, and nothing in that environment hinders communication with an Arduino. So, what's best for me is best because of "familiar and will work" and we can't decide what meets those criteria for you.

If you will update your question to describe more about your application, details about your interface, users, and what skills you have, then I will update this answer, but as it stands "the world is your oyster" because almost any programming environment capable of making an application will be able to interface with Arduino in some way.

For "graphical" programming look into LabView - I can think of a lot of reasons to not go that way though.  http://www.ni.com/labview/

Here's a tutorial for interfacing a c# application with Arduino:
http://www.codeproject.com/Articles/473828/Arduino-Csharp-and-Serial-Interface

The gist of it is this:

  1. Some version of Visual Studio up and running - you can use the free version mentioned in Jon's answer (Express version for desktops).
  2. A working Arduino connected to your computer with the USB.
  3. Create a new Windows Forms Application and drop whatever controls you need onto the form
  4. Write your Arduino-connecting code into the events of the controls

That is the basic method of creating Windows Forms apps regardless of what you're doing. You create forms with controls and your custom code goes into the events of those controls. If you read the tutorial it explains how that code works, but here's a sample... (In the tutorial, they are doing a WPF app, which is slightly different from Windows Forms in how the controls are defined, but the code is basically the same). This is an event of the serial port - you respond to the event by displaying the received data into a text box. Very simple!

    void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) {
        string data = mySerialPort.ReadTo("\x03");
        myForm.myTextBox.Text = data;
    }

body:
The "best" software for me is the free Visual Studio Express for Desktops.

Using C#, I would add a SerialPort component to the form, configure it for the same COM port as the Arduino/FTDI, then send commands to it.

![VS][1]
Visual Studio is "stupid simple" (I'm not implying anything :D). Double-click Button in the toolbox(1) and it creates one. Double click the button(2), and it outlines the code and attaches the Click event to it for you. Double click Components>SerialPort(3) to create one. My code is highlighted in blue to the right and this took all of 1 minute to create.

To point you in the right direction on the Arduino side, here is the structure of the "command" I sent in the screenshot:

    XXXYYYZZ
    Where:
    XXX = 000b for "turn off", 001b for "turn on", 010b for "toggle", 011b for "read pin"
    YYY = Pin number //Max = 111b = 7 (+ 0) = 8 uniquely addressable pins (using 3 bits)
    //Pin number does not have to match the MCU port/pin designations
    //MCU will convert logical pin #'s 0-7 into the correct physical port+pin
    //For more pins, steal another bit from ZZ; Max for YYYY = 1111b = 15
    ZZ = Spare bits //Tell the Arduino whether to acknowledge or not, etc.

    00100100b = "Set pin 1 high"
    01001000b = "Toggle pin 2"
    10000000b + 0xAA (two byte command) = "Reply with contents of register 0xAA"

Additional commands can be created to tell the Arduino to reply with a specific variable or status.

    bool isRegisterRead = false;
    bool isMultiByte = false;
    while (true)
     if (wasByteReceived) //This flag is set in the RX interrupt and the byte is saved to byteReceived
      if (isMultiByte) //Second byte received
      {
        if (isRegisterRead)
        {
          //We need to read and send the value of the register at the address in byteReceived
          ReadAndSendRegisterValueAtAddress(byteReceived);
          isRegisterRead = false;
        }
        else DoSomethingWith(byteReceived);
        isMultiByte = false; //Start over
      }
      else //First or only byte received
      {
        //Consider using a ZZ bit to indicate more data instead of listing them explicitly
        if (byteReceived == 0x80) //A multi-byte "read register" command
        {
          isMultiByte = true; //Next byte received is money
          //For my example we need to set a flag somewhere to indicate that we are reading a register
          //isRegisterRead should be set to true by DoSomethingWith
        }
        //Is there any processing for the "command" byte? (i.e. extract and save the pin number)
        DoSomethingWith(byteReceived); //Process one-byte command or first of two-byte command
      }

  [1]: https://i.stack.imgur.com/XNkmg.jpg

body:
3 votes for visual studio and a windows desktop, although I would chose WPF. Win32 (Winforms) is a slightly out of date architecture. WPF has a steeper learning curve, but worth it if you want to become proficient. If it is a one off application, don't bother, use winforms.

I'll add a couple of points.  Debugging Arduino sucks. I am being kind.  The Arduino IDE deploys on com port 1, and prints debugging messages on com port 1, so if you need to communicate un-interrupted by debugging and deployment, what do you use? Not com port 1 for sure. Look at software serial in the beginning and assign ports around its requirements.

Second, writing your own com stack is dumb, yet is done 99% of the time.  Look at MQTT if ethernet is available, MQTT-SN if it is not, [CmdMessenger][1] or [CommandSerial][2] or something similar or spend days designing, writing, re-writing and debugging your own, your choice.

  [1]: http://playground.arduino.cc/Code/CmdMessenger
  [2]: http://playground.arduino.cc/Code/SerialControl


body:
I am building a wireless system that has got an Arduino with a XBEE as the 'end user' and I need to acquire data/control that Arduino from a PC graphical interface.
As far as I'm aware there are two options to obtain the communication:

1. I could use another Arduino with XBEE (coordinator) that is connected to my PC (serial) to control the 'end user'. The code is stored in this Arduino which works as a bypass between PC and XBEE.

2. I could simply use a XBEE without Arduino (coordinator) connected to my PC to control the 'end user'. The code should be stored within the PC or the XBEE to establish communication and control data transmission to different end users (???)

As I am new to the Arduino world, would you please direct me to the best/easiest solution to obtain such thing?

title: XBEE coordinator WITH or WITHOUT Arduino?

Answers: 1

body:
If you want just to control and receive data from your end user, option 2 is easy to implement.

You can use any programming language that supports serial communication such as python, node.js, etc.

What you have to is to note how your coordinator is recognized by your operating system (in windows as com1 port, unix-like as ttyACM or similar) and open it from your preferred language.

After that, you establish a protocol that should be agreed with your Arduino. For example. Suppose you want to collect data from end user, so, you send a message from the coordinator connected in your PC with a code #data through the serial. When the Arduino receives it, it decodes the message and return something like #d125 where it says it is sending the data and the value is 125 (supposing integer values).

Making sure you already have configured the XBees in the same network by setting Same PAN id and cross setting the destination address of each one so they send packates to each other.

I am supposing you are using AT transparent mode where they just send whatever comes in the serial interface, in this mode they work basically sending chunks of bytes and it is up to you to establish a protocol to provide a good flow of data. In this mode there is no guarantee that your packet will reach the destination. In order to fully extend the XBee usage, you'd need the API mode where all the transmission checks are done.

But for you purpose, AT mode seems enough.


body: I am new to arduino programming. I want to sense temperature and send it to a server in my college. I am using Arduino Uno R3 board which has ATmega 328P micro-controller. I am able to get serial output on my PC but is there a way in which I can send temperature data to the server in a packet format using Arduino Programmer and not using Ethernet Shield ? Please answer in a less complex way.

title: Arduino over a Network

Answers: 2

body:
Without an ethernet shield or some kind of other internet connectivity shield/circuitry you cannot communicate directly with the internet through the arduino. However, if having a computer as the internet communicator isn't a problem you could try a setup like:

arduino->serial (usb)->[processing][1]->[internet][2]

This way you create the internet packet in processing using the temperature information received through serial from arduino.

see also https://processing.org/

  [1]: https://learn.sparkfun.com/tutorials/connecting-arduino-to-processing
  [2]: http://forum.processing.org/one/topic/how-to-access-internet-through-processing-application.html

body:
Use an [Arduino Yún][1]: it's a Leonardo coupled with a CPU running GNU/Linux (a flavour of OpenWRT).

Using the Bridge library, your sketch can delegate tasks to the linux side.

HttpClient example (Examples > Bridge > HttpClient) GETs a page from the Arduino web site, but the HttpClient class may POST whatever data to a server of choice.

There is also a nice example called [SendDataToGoogleSpreadsheet][2] (Examples > Bridge > Temboo > SendDataToGoogleSpreadsheet): it accumulates sensor readings on a google spreadsheet. I've used something like that on a [project of mine][3].

  [1]: http://arduino.cc/en/Guide/ArduinoYun
  [2]: https://www.temboo.com/arduino/yun/update-google-spreadsheet
  [3]: https://github.com/ffissore/badger


body:
I'm trying to do some fairly simple serial communication and have things partially working, but am pretty confused about a couple results I'm getting.

For a little background, I'm using an Arduino Mega 2560 to try to communicate with a Dynamixel servo (MX-64) over TTL (half-duplex, asynchronous) with Tx1 and Rx1.  Basically I construct some byte arrays as instructions, send them over to the servo (with `Serial1.write()`), and then read back a reply.  I've actually gotten it to work pretty well if I use `Serial1.readBytes()`, specifying the length of the buffer (number of bytes I'm expecting).  I'm also reading back what I originally sent (first) as well as the response (second), since I have Tx1 and Rx1 tied together (required in my setup because this servo only has one data wire).

However I don't understand the difference between `Serial.readBytes()` and `Serial.read()`.  If I do `Serial.read()` just prior to `Serial.readBytes()`, it comes back with -1, meaning no bytes to read... but then `Serial.readBytes()` gives me the byte stream I was expecting from the buffer!  What's going on here?

Similarly, `Serial.available()` seems sort of broken in that it tells me there are no bytes to read (returns 0), but then I can read the bytes I'm expecting with `Serial.readBytes()`. Additionally, I can do `Serial.readBytes()` after there's nothing left (or rather, there shouldn't be any bytes left...) and it will give me some bytes, but they're total garbage.

I think maybe there's something I don't understand about the way the serial buffer works, but can't find a good resource on it and the Arduino reference pages are kind of useless.  Any clues about the difference in how these operate would be much appreciated!

title: Serial.read() vs. Serial.readBytes()?

Answers: 1

body:
readBytes is blocking until the determined length has been read, or it times out (see Serial.setTimeout()). Where read grabs what has come, if it has come in. Hence available is used to query if it has.

Note that it takes time for a message to go out and to receive either the echo or response. So simply checking the RX buffer immediately after sending something, is expected to be empty for some time. That is where readBytes sites and waits. And I bet the default setTimeout of 1s is sufficient, to get the response.

This is why you see the Serial.read() inside a while or if Serial.available. Hence I typically employ something like the following: Which emulates readBytes (for the most part).

  #define TIMEOUT = 3000;
  loop {
   char inData[20];
   unsigned long timeout = millis() + TIMEOUT;
   uint8_t inIndex = 0;
   while ( ((int32_t)(millis() - timeout) < 0) && (inIndex < (sizeof(inData)/sizeof(inData[0])))) {
    if (Serial1.available() > 0) {
     // read the incoming byte:
     inData[inIndex] = Serial.read();
     if ((c == '\n') || (c == '\r')) {
      break;
     }
     Serial.write(inData[inIndex++]);
    }
   }
  }

Above code was quickly written and untested. But gets the idea across.


body:
I want to write my own debugger.

I've found [Visual Micro][1] plugin for Visual Studio provides Arduino Debug.

So, does anyone have ideas how it works?

I just desire make the same plugin in Eclipse IDE.

  [1]: http://www.visualmicro.com/

title: How do I write a debugger for Arduino?

Answers: 1

body:
Assuming you have enough time and money to spend on this project. ($50 is a bargain for a debugger, believe me. About a decade ago I wrote an assembler/debugger suite for a very small niche market microcontroller, the Maxim Integrated MAX1464, using a combination of SciTe and Perl/Tk. Writing your own debugger is a great educational project, if you have the time and money to complete it.)

**Tools**

Assuming you already have all the standard Arduino debug tools, and just want to learn the process of making a debug tool.

Assuming you've used the standard Arduino debug tools before, and written enough programs (sorry, you Arduino guys call them "sketches" for some reason) so that you have some code you feel comfortable debugging on. Setting a breakpoint in a simple "blinking LED" program isn't very satisfying, better to set breakpoints in a test program that actually does something. You'll also want to have some branching logic pathways to test breakpoints, and some variables (counters perhaps) so you can test reading values through the debug interface.

Assuming you have a couple of spare Arduino boards, because very likely during development some bad debug commands may get sent. Ideally you should have a device programmer capable of restoring the Arduino bootloader image that normally resides in the Atmel AVR processor. Sending arbitrary commands to the debug interface could possibly erase or mess up the bootloader.

Assuming you have access to customary EE lab tools: DMM, oscilloscope, soldering iron, etc.

**Research**

Assuming you already know how to make an Eclipse IDE plugin... (if you don't, that would be a question to research on Google or StackOverflow.) I'm treating this the same as if you were writing a plain command-line debugger or a gdb driver.

I'm not really sure which debug protocol you need to implement. Sadly, `JTAG` doesn't seem to be supported by Arduino. The `ICSP` in-circuit system programming header might give debug access, though it would require attaching some hardware to the board that you're debugging. If I understand correctly, the Arduino IDE supports debugging through the USB port, which is a very attractive setup.

Assuming you plan to use Atmel's proprietary `DebugWIRE` protocol, which someone else has kindly attempted to reverse-engineer here: http://www.ruemohr.org/docs/debugwire.html  Ideally you'd get the real documentation from Atmel. The hazard of a reverse-engineered protocol like this (aside from possible IP infringement) is that the protocol could change without notice. Not having direct access to the team that designed the microcontroller, means you have to rely on whatever documentation you can find and whatever else you can discover experimentally.

Assuming you can use the USB bridge chip's `DTR#` to drive (and possibly sense) the RESET pin, to access DebugWire. If that USB bridge chip is an FTDIchip.com device, you'll want to use the bit-banging mode to drive and sense DTR#. (In normal "RS232 mode" this pin is not bidirectional.) Go to the FTDIchip.com website to get the D2XX programmer's guide and example code.

Since DebugWire is a protocol that uses one wire for all signalling, both directions, timing is absolutely critical. **You must use an oscilloscope** to observe the DebugWire signals on the RESET pin, otherwise you're "flying blind".

That should be enough to get you started. Initially, you'll have to figure out how to discover an attached Arduino, enter debug mode, set a breakpoint, and reset the part back into free-running mode. The "blinking LED" test program is good enough to see some results for this early stage.

Cheers


body:
I have Sparkfun Pro Micro (Leonardo compatible board). I got it because I plan to build my own array of controls for use in flight/racing sims.

My starting point is LeoJoy, and I didn't have any trouble getting this up and running. Installed just fine, and I have a programmable HID joystick available in windows. It seems to work by modifying the RAWHID code in the default libraries to spoof being a HID joystick. However, my board was now stuck in joystick mode, with no available COM ports for uploading new sketches.

Resetting the board (by grounding the RST pin), enables the COM port, but very, very briefly. Not enough time to send new sketches.

After about an hour of trying different timing, I finally did upload an empty sketch to the board before it went into Joystick mode. So I'm good for now, but I'm a bit worried that I'm going to have to repeat this every time I want to make a change to my program.

Am I doing something completely noobish here? Is this the correct way to program a board that has been forced to act as a joystick? Is there a better way?

Perhaps there's some code I can put into my sketch that will delay the change of USB behavior for a few seconds. That way, it will allow me to recompile and submit my sketches after a reset without having to rush the timing.

title: Uploading new sketch to Leonardo-type boards when you've changed the HID mode

Answers: 1

body:
From Sparkfun's page [Pro Micro Hook-upGuide][1]

When a Pro Micro is externally reset (by pulling the RST pin low), it’ll only briefly (<750ms) start the bootloader before continuing on to the sketch. If you need the bootloader to run longer, resetting twice quickly will get the Pro Micro to enter bootloader mode for eight seconds.

Hope that helps! If not there are some other procedures you might want to look into.

  [1]: http://f


body: I am not entirely sure how a magnetometer works in IMU units, so I was wondering how a magnet near the sensor affects readings?

title: Will a magnetometer give distorted values if there is a magnet near?

Answers: 2

body:
> Will a magnetometer give distorted values if there is a magnet near?

Yes, effectively.

In fact no, as the reading it gives WILL BE the field at that point BUT the field will be distorted compared to what you would see when the magnet is absent.

The effect of magnets at a distance is a somewhat complex subject - especially when there are several presnt and/or where ther are "magnetic materials" present but, as a guide.

 - At a distance large compared with magnet dimensions the field falls as the cube (not square) of the distance.

 - Very rough but useful rule of thumb: A top-end rare earth magnet will produce a field of **about** 1 Tesla at a distance of  1/2 it's thickness from the centre of its pole face. So eg a 20mm thick circular magnet will produce ABOUT 1 T at 10mm from the centre of its pole face. This is more useful in motor or alternator applications than when using magnetometers.

body: The IMU magnetometer is made to measure the magnetic filed of the earth, which magnitude is a few 10 - 60 uT (micro-Tesla). You cannot measure it near to a large magnet that may generate 1 T or more: the magnetometer will saturate.


body:
    #include "pulse-sensor-arduino.h"
    #include "Arduino.h"
    #define PulseSensorbegin

    int pulsePin = 0;
    int blinkPin = 13;
    int fadePin = 5;
    int fadeRate = 0;
    volatile int BPM;
    volatile int Signal;
    volatile int IBI = 600;

    volatile boolean QS = false;

    void setup(){

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

      PulseSensorbegin();

    }

    void loop() {

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

       ledFadeToBeat();

       delay(5000);
    }

    void ledFadeToBeat(){

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

    void sendDataToProcessing(char symbol, int data ){

        Serial.print(symbol);
        Serial.println(data);
      }

/// my  ccp program

    #include "pulse-sensor-arduino.h"

    volatile int rate[10];
    volatile unsigned long sampleCounter = 0;
    volatile unsigned long lastBeatTime = 0;
    volatile int P =512;
    volatile int T = 512;
    volatile int thresh = 512;
    volatile int amp = 100;
    volatile boolean firstBeat = true;
    volatile boolean secondBeat = false;
    volatile boolean Pulse = false;
    volatile int pulsePin;

    volatile int PulseSensor::IBI = 600;
    volatile int PulseSensor::BPM;
    volatile int PulseSensor::Signal;
    volatile boolean PulseSensor::QS = false;
    void PulseSensor::begin(int pPin)
    {
      pinMode(pulsePin, INPUT);
      pulsePin = pPin;

      TCCR1A = 0x00;
      TCCR1B = 0x0C;
      OCR1A = 0x7C;
      TIMSK1 = 0x02;
      sei();
    }

    ISR(TIMER1_COMPA_vect)

    {
      cli();
      PulseSensor::Signal = analogRead(pulsePin);
      sampleCounter += 2;
      int N = sampleCounter - lastBeatTime;

      if(PulseSensor::Signal < thresh && N > (PulseSensor::IBI/5)*3)
    {
        if (PulseSensor::Signal < T){
          T = PulseSensor::Signal;
        }
      }

      if(PulseSensor::Signal > thresh && PulseSensor::Signal > P)
    {
        P = PulseSensor::Signal;
      }

      if (N > 250){
        if ( (PulseSensor::Signal > thresh) && (Pulse == false) && (N > (PulseSensor::IBI/5)*3) )
        {
          Pulse = true;
          PulseSensor::IBI = sampleCounter - lastBeatTime;
          lastBeatTime = sampleCounter;

          if(secondBeat){
            secondBeat = false;
            for(int i=0; i<=9; i++){
              rate[i] = PulseSensor::IBI;
            }
          }

          if(firstBeat){
            firstBeat = false;
            secondBeat = true;
            sei();
            return;
          }

          word runningTotal = 0;

          for(int i=0; i<=8; i++){
            rate[i] = rate[i+1];
            runningTotal += rate[i];
          }

          rate[9] = PulseSensor::IBI;
          runningTotal += rate[9];
          runningTotal /= 10;
          PulseSensor::BPM = 60000/runningTotal;
          PulseSensor::QS = true;
        }
      }

      if (PulseSensor::Signal < thresh && Pulse == true){
        Pulse = false;
        amp = P - T;
        thresh = amp/2 + T;
        P = thresh;
        T = thresh;
      }

      if (N > 2500){
        thresh = 512;
        P = 512;
        T = 512;
        lastBeatTime = sampleCounter;
        firstBeat = true;
        secondBeat = false;
      }

      sei();
    }

//my header programing

    #ifndef PULSE_SENSOR_ARDUINO_H
    #define PULSE_SENSOR_ARDUINO_H

    #include "Arduino.h"

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

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

    #endif

title: arduino program got error expected //primary-expression before ')' token error: //expected ';' before '}' token E

Answers: 1

body:
At the top of your program you have this:

    #define PulseSensorbegin

which defines `PulseSensorbegin` as nothing

Then later you have:

    PulseSensorbegin();

which the pre-processor turns into:

    ();

which is where the error is occurring.


body:
I want to interface my barcode scanner with an Arduino using RS232. I have connected 2 (RX), 3 (TX) and 5 (GND) of the RS232 with the corresponding pins of MAX232. I am taking TTL outputs on Arduino pins 6 and 7.

This is the code of the Arduino program:

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(6, 7); // RX, TX

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

    void loop() {
      // run over and over
      if (mySerial.available()) {
        byte x = mySerial.read();
        Serial.println(x);
      }
    }

I am not getting any output on the serial monitor when I scan a product.

title: How to get serial data in Arduino from a barcode scanner?

Answers: 3

body:
Assuming your Arduino has only one hardware serial connection (it's something like an Uno rather than a Mega) you're quite right in using software serial, the Arduino will already be using pins 2 and 3 to communicate via USB to the Serial monitor so you can't use them to communicate with the scanner.

However carefully look at your first line of code, you've asked software serial to use pins 6 & 7 yet hooked the barcode scanner to pins 2 & 3. Move those pins over to the one's you've specified.

Secondly in your setup function you've begun communication with hardware Serial but not software serial. You'll need to add something like mySerial.begin(XXX) where XXX is the baud rate for the scanner.

Finally you haven't told the Arduino what pinMode to use for 6 and 7. You'll want pinMode(6, INPUT) and pinMode(7, OUTPUT) in there too.

body:
RS 232 works on different voltage levels than Arduino, I believe the values you are getting on the screen will have no meaning whatsoever, If the scanner output is TTL then yes it would work, but in my own experience that logic is inverted and you have to add a 1 to software serial:

SoftwareSerial mySerial(6, 7, 1); // RX, TX

The first step is checking what voltage level is given by your scanner output.

body: I tried this as well, for some reason it is NOT WORKING on pins 6 and 7, but it works perfectly using pins 10 and 11 instead. Of course, you still need to add the `mySerial.begin()`.


body:
I have been tasked to find a way of communicating to a webservice from my microcontroller - yay!

With little-no real grasp on sms/etc (due to not ever 'using' it before), it appears that my knowledge of GPRS is, well, none existent.

So, I've come here in hope that someone could tell me if there is such a way for a microcontroller to 'send data out' though, well, a 'sim card' via an sms message.

**********

This has left me a little lost If i'm honest.

My project involves 'tracking' a vehicle (still working on finding a GPS module for that), and then sending the coordinates back to HQ at hourly intervals (via text message).

So, My obvious question is this: *What GPRS sim card module will allow me to do this?*

I read [here](https://arduino.stackexchange.com/questions/1194/which-shield-to-use-for-gprs), although the accepted answer there for a chip requires external power, and so is of no 'true' use to me as the whole unit needs to be powered and left 'unattended' for long hours at a time.

seeing as I also need to 'monitor current location' of the board, I am also in need to obtain a GPS location.

I was thinking that mobile phones have both of these cababilitys - is this done with a 'sim card module', or is there a way of 'one module does both - send an sms AND can also gain current GPS location'?

**************
Sorry if this is too broad, but I'm certainly not 'gifted' in knowing too much about these technologies (esp. when all these acronyms use similar letters).

Any advice / input here would be very helpful.

title: Board recommendations for GPRS/GSM for 'on the go'

Answers: 1

body:
I have a project that have the same idea that yours.

I used Ublox NEO-6M GPS Module for GPS tracking, the module cost in a range from $6 to $13 USD(it depends from where the seller ships, china o USA) in EBAY. You can connect it via UART.

For the internet I used a SIM800L V2.0 5V Wireless GSM GPRS MODULE, you can buy it from EBAY too, it cost no more than $10.00 USD, and you can connect to internet or send SMS using AT commands.

I used a combination of arduino and Raspberry pi zero, also I send the GPS data to a webserver (I pay 5dllr/month for a VPS) and then I can track using google maps.

Thats the basic information, you can use it to start working.


body: I want to connect 20 serial devices to the same Arduino Mega.How to do this?I know that multiplexing is the way but how to do that

title: How to connect twenty different serial devices to an Arduino Mega?

Answers: 2

body:
You say that they are working on RS232 - which is an electrical standard.  You may mean that they use standard UART style asynchronous serial communications - perhaps at 0 to 5V electrical levels.

It depends on how fast you need to communicate, and how continuously you need to communicate.   If you can choose when to communicate with each device, you may be able to use Soft Serial with multiple pins.  Be aware that it cannot both transmit and receive at the same time (one or the other), and it can only communicate with one port at a time.  So it might work for you if you can communicate with one device for a while, then ignore it while you check with other devices, one at a time.

Otherwise maybe not.  For example, if you need to receive from many devices at times of their choosing so you need an always-on hardware UART for each device.  There are 4 hardware UARTs in the MEGA, so 4 would be your limit.

There are things like external UART peripherals, but managing that would likely be very hard for you.

body:
You can use the SoftwareSerial library and declare instances to communicate with your serial devices. I am not sure if you can declare 20 such different instances but if at all you do, use the function: [listen()](https://www.arduino.cc/en/Reference/SoftwareSerialListen) to switch between those serial devices. This, probably, is as close as it gets to multiplexing as you mentioned.

I've tried with 2 such SoftwareSerial instances for communicating with GPS module and GSM module and the listen() function worked flawlessly.

Cheers!


body:
Is it possible to connect 6 dc motors and 2 dc servo motors to an Arduino Uno? I intend to control the Uno with a Raspberry pi connected through USB.

Assuming every motor to be bidirectional, how many L293 or L298 motor driver boards do I need? Is there any other better option than using multiple driver boards?

title: 6 + 1 motors connected to an arduino uno?

Answers: 2

body:
Normally a full H-bridge (for one motor in bi-directional mode) will need 3 ouput pins. You can potentially force the enable pin to a constant level but that means you will always draw current for your motors even when they don't move, which is probably not what you want. ou might also wire all 6 enable pins together to one Arduino pin just to control power of all motos altogether.

In addition, each servo will need one output pin (typically 9 and 10 for both servos).

Hence in the worst case, you would need 20 pins overall. You have them on Arduino UNO but this means you don't have anyhting else left, even Serial communication!

If you can wire all 6 enable pins together, then **you will need "only" 15 pins**.

Also, note that if you want to **control the speed of the DC motors**, you will need PWM pins, but then **you won't get enough with a UNO**.

Regarding drivers ICs (**L293 or L298**), each of them has 2 full H-bridges, hence can drive 2 DC motors in bi-directional mode, so **you will need 3 of them overall**.

body:
TI is only one of the many manufacturers who make some really nice motor control chips.  The  DRV8835 is one such device: it will drive two motors at voltages up to 11 Vdc at currents up to 1.2 Amps each.  Each channel requires two control lines: enable and direction.

[Pololu][1] sells this chip already mounted to a carrier board for a rational price.

You will need a total of (6 motors * 2 lines per motor) = 12 i/o lines PLUS two more lines to control your servos for a total of 14 i/o lines from your controller.

  [1]: https://www.pololu.com/product/2135


body:
I have developed a program and the idea is that when it receives serial data (any single character) it returns a single random number.

I have it working but it returns 3 x random numbers one after another for each read that it does and I can't figure out why.

    int led = 13;
    char incomingByte = 10;
    long randNumber;
    // the setup routine runs once when you press reset:
    void setup() {
      // initialize the digital pin as an output.
      pinMode(led, OUTPUT);
     Serial.begin(9600);
    }

    // the loop routine runs over and over again forever:
    void loop() {

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

       if (Serial.available() > 0) {
                    // read the incoming byte:
                    incomingByte = Serial.read();
                    // say what you got:
                  //  Serial.print("I received: ");

                    randNumber = random(1, 2000);
                    Serial.println('PL' + randNumber);
                      digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
                      delay(1000);               // wait for a second
                      digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW

    }

    }

title: Writing serial data, just once after read

Answers: 1

body:
When you enter a single character into the Serial Monitor and press Enter, three bytes are sent: the character, a carriage return, and a linefeed. `Serial.read()` only reads a single byte, so data is available three times.

Either loop reading until no more bytes are available, check for and discard any CRs and LFs, or use a serial terminal that doesn't require pressing Enter to send data.