body:
I had posted some questions about this project earlier this week. Arduino uno + w5100 ethernet shield + nrf24l01 transeiver.

The w5100 is running a webserver to accept GET requests and parse out the variables - Works all the time

The nrf24l01 is acting as a transmitter and sending data out to other nodes - Only works with no Ethernet code.

What doesn't work is both at the same time. With everything hooked up it parses get fine, gets the variable but I can't transmit it since the radio never seems to fire up. Remove all the ethernet code and leave just the radio code it sends fine.

Code here. http://pastebin.com/SMWC9x4F it errors at 146. Which I assume is the radio never starting since the:

    radio.printDetails();

does nothing.

I'm using manicbug's library.

I use the EXACT same send bits in that file to test wireless communication, it works. I only need it to transmit wirelessly when it get data from the network.

Pinouts:

CSN -> 10
CE   ->  9
MISO -> 12
MOSI -> 11
SCK   -> 13
VCC   ->  Separate 3.3 source, not the arduino
GND  -> GND

My guess is this is because both are using SPI.

Tried the softspi method http://pastebin.com/4mv612B7 .

Same thing. I can post GET to it, parse out variables but nothing on the radio side. And I still get no output from radio.printDetails() so it just must not be starting. Commence hair pulling..

EDIT: Bloody hell, printDetails() relies on printf...... that would have been handy to figure out an hour or two ago.  I can get details now. still having communication issues.  Will post more debugging information in a bit.

title: w5100 and nrf24l01 - SoftSPI - Radio not starting

Answers: 2

body:
Issue one:  .printDetails(); uses printh.  If you don't have that included you won't get the information.

Issue two:  The ide gets confused when you have two libraries with the same file.  I compiled my receiver with the softspi file. Once I put the right library in it works.

body: The issue here is that the Ethernet chip locks the SPI bus thus making it impossible for NRF24L01+ to communicate with the arduino properly. Please use softSPI to fix this.


body:
I'm working on project 9 of the arduino starter-kit - the motorized pinwheel.

Here is the schematic:
![enter image description here][1]

The diode in question (and the only one here) is toward the bottom right of the breadboard. It is to prevent the back-voltage from the motor from harming the circuit.

According to the above img, would the backvoltage travel back down the motor's supply of energy (the red wire)?

If so, what is the diode preventing here? That whole energy strip will just have current running through it and the diode's cathode will prevent it from running to the transistor - which would also happen fi we just didn't connect anything to that power strip.

If not, and the back-voltage is running through the black wire (our ground), then I still do not see how the diode is helping. The diode seems to want to pull the extra energy back to our power strip (which is why the anode is facing toward the left, where the motor's output is. But this doesn't prevent the current from still hitting the green wire which leads to the transistor's 'source'.

So how is this diode working?

Thanks!

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

title: How is the diode here effective?

Answers: 2

body:
Under normal operation the + connection of  any inductive component (motor, relay, etc) is at a higher potential than the - connection.

During a "back EMF" event (the collapsing of the magnetic field) a large voltage *of the opposite potential* is generated.  That means that the - connection suddenly becomes a much higher potential than the + connection.

That is very bad for anything connected to the - pin of the inductive load.

With the diode connected backwards like that across the inductive load, under normal operation, it does absolutely nothing.  However, when the - pin becomes a higher potential than the + pin the diode will become *forward biased* and start to conduct.  That allows a very low resistance path for all the energy stored in the coil of the inductive component to flow from the high potential to the low potential, which is what it wants to do.

Without it, the only way for that energy to get from the high potential to the low potential is through the rest of your circuit, which it won't like.

The excess energy at the - side of your motor wants to get to the + side. That's the only place it wants to go.  It'll (crudely speaking*) take the shortest, quickest, route to get there.  That means it goes through the diode and nowhere else.  Straight from the black wire to the red wire of your motor.

----
<sub>* Note: In actuality the energy will take all possible routes at once, but in varying proportions depending on the resistance of the route.  The lower the resistance the greater the proportion. Because the diode is such low resistance it gets the majority of the energy and only a very negligible proportion takes the other possible routes through your circuit. Unless your circuit is incredibly sensitive it won't even notice it's there.</sub>

body:
Flywheel Diode.

When the transistor shuts off, the stopping of the motor generates *back EMF (ElectroMotive Force)* . This manifests itself as negative potential difference (voltage) across the motor. In plain English the collector of the transistor, connected to the -Ve side of the motor, is raised to a damagingly high voltage. If you include the diode, this voltage is siphoned immediately back to the positive rail, so the damage is averted.


body:
I have arduino nano and sim900a modem.
![My arduino pinout][1]

![SIM900A Modem][2]

![Modem Backside][3]

Rx(pin30) and Tx(pin31) pins of **arduino** shows 3.8VDC respectively and Rx and Tx of **SIM900a** shows 3.6VDC and 2.8VDC respectively. Could i connect the SIM900a modem directly to the arduino? Since Should i use level shifter between arduino TX(3.8v) and SIM900A modem(3.6v)? Any suggestions?

Thanks..

  [1]: https://i.stack.imgur.com/Ze9I6.jpg
  [2]: https://i.stack.imgur.com/wpPOc.jpg
  [3]: https://i.stack.imgur.com/kXEOE.jpg

title: How to interface arduino nano with sim900A?

Answers: 1

body:
The bottom of your board shows a chip that gives every hint of being a charge-pump logic-level to RS232 inverting level shifter, to translate from the SIM900A's levels to the RS232 D-Sub connector.

It would appear that the 3 pin header just inside the D-sub would allow you to communicate at these levels.

However, a quick look at the SIM900A docs I could find **suggests that these logic levels may be 2.8v, NOT 3.3v, and 3.3v is actually outside absolute maximum rating!**

Essentially, you have two problems:

 1. You need to drive and read signals with 2.8v logic, either by modifying your arduino to run at that voltage, or by using a level shifter.  It's possible that a resistor would protect the SIM900A, but that is going to be the most expensive component and so short of finding solid evidence of input protection diodes I'd be more hesitant to do that here than I would in other cases.

 2. You need to make the level shifter not drive a signal into the SIM900A, so you don't fight with it.  You could do this by looking in the documenation (if any) for your board and seeing what accommodations they made for this, looking up the level shifter's  data sheet and finding the enable pin, or merely desoldering it.

Another option would be to make your Arduino talk at RS232 levels using its own shifter board.

Finally, there's a sort of hackish option:  Connect the *transmit* data from the SIM900A to a 3.3v Arduino, but connect the transmit from the Arduino through a simple inverter (tinylogic, whatever) to the RS232 *receive* pin.


body:
I was trying to apply PI controller to a motor using Arduino. I have somewhat achieved the task but the problem is that it oscillates too much. Also i couldn't figure out what to do when pwm signal are calculated as negative

      int counter = 0;
      double end_time=0;
      double ini_time=0;
      double rpm=0;
      double my_time=0;
      double temp = 0;
      int pid_speed=0;
      float kp=2.25;
      float ki=.01;
      float kd=0.005;
      int prev_error=0;
      double pwm_sig=0;
      int integrator  = 0;
      int motor_sig_pin= 5;
      int error=0;
      int absolute = 0;
      float desired_rpm=1000; //my desired RPM value
      double zero_time=0;
      double i_time=0;
      double f_time=0;
      int rpm_tacho=0;
      int previous_error=0;
      int derivative=0;

      void setup() {
        pinMode(2,INPUT);
        digitalWrite(2,HIGH);
        pinMode(motor_sig_pin,OUTPUT);
        pinMode(9,OUTPUT);
        pinMode(10,OUTPUT);
        digitalWrite(9,HIGH);
        digitalWrite(10,LOW );
        attachInterrupt (0,Count,RISING);
        ini_time = micros();
        i_time=micros();
        Serial.begin(115200);
      }

       void Count(){ //calculating time for one round using encoder

          counter++;
          if (counter>=100){
            end_time=micros()-ini_time;

            ini_time=micros();
            counter=0;
          }
       }
      void loop() {
          rpm = ((1000000*60)/(end_time));
          rpm = abs(rpm);
          rpm_tacho = ((1000000*60)/(zero_time));
          if (rpm <10 || rpm>5000){
            rpm=0;
          }
          error=desired_rpm-rpm;

          integrator += error;
          pid_speed = kp*error; + ki*integrator;

          pid_speed=(int)pid_speed;

          Serial.print(pid_speed);
          Serial.print("       ");

          if (pid_speed> 0){
            if (pid_speed>255)
              analogWrite(motor_sig_pin,255);
            else
              analogWrite(motor_sig_pin,pid_speed);
          }
          if(pid_speed<0){
            if(pid_speed<-255)
            {
                analogWrite(motor_sig_pin,0);
            }
            else
           {
              pid_speed=abs(pid_speed);
              analogWrite(motor_sig_pin,255-pid_speed);
           }
          }
          Serial.print ("      ");
          Serial.println(rpm);
      }

title: PID control for Motor Speed control

Answers: 2

body:
Instead of thinking of the PID output as pid_speed, think of it as motor_power, and what the PI controller is doing is translating errors in rpm into a motor power setting.

You are probably getting oscillation because of integral windup.  If your loop is fast relative to your system, each loop worth of error adds to integrator quickly/quicker than the system can adjust.   For example, if a loop takes 1ms, an error of 100rpm could overflow the "int integrator" past 32768 in only 0.327 seconds, and past the threshold where the integrator could peg the output 25500 (=255/Ki) in only 0.255sec  If the integrator is faster than the system, it can easily cause overshoot.  You might consider slowing the loop down to 10ms, 100ms or 1000s to match the physical process and make the kI term be a sane conversion of the integrator's rpmError*seconds/100, rpmError*seconds/10, or rpmError*seconds into output power.

To handle the numerics and constraints better, like overflowing integrators and negative output values, it would probably be best to use the Arduino PID library from http://playground.arduino.cc/Code/PIDLibrary as in Edgar Bonet's comment.

body:
I do not know if this question still exists or you managed to solve it. Regardless, I was (still am) working on a [self balancing robot](https://github.com/NischalSehrawat/Self-Balancing-Segway-Robot) where I also faced such an issue and I came to this forum. The way I tackled it was to set PID outputs (assuming you are using Arduino 's PID library) 0 - 255 instead of -255 to 255. Now for my project I needed to change direction of the motor depending upon the inclination angle of the robot. So, each time I need to change the motor rotation direction, I do the following

-  I first reset the Iterm (or make it zero).
- Change the direction of rotation.
- Begin PID computation again.

Earlier I was also trying to achieve this by -255 to 255, but it was very jerky and I was not sure if that was the correct way to do it. With my current approach, I have managed to solve my problem.


body:
I am a newbie in arduino. I successfully installed driver for arduino atmega 8l, which were provided by the company i bought arduino from. The driver is PL2303 by prolific. The reason i m mentioning this is because at first i had some problems in installing them.
Now after i have made a blink program. I thought of uploading it. Whenever I try to upload i get this error:
avrdude: arduino_read_sig_bytes(): (a) protocol error, expect=0x14, resp=0x75
avrdude: error reading signature data for part "ATMEGA8", rc=-2
avrdude: error reading signature data, rc=-1

My computer: Windows 7 32-bit
I tried pressing the reset button before uploading, i get the same message.
I tried it in another computer of mine. There the driver is showing a code 37 error so basically my other computer is not reading the arduino.(also my board comes with bootloader already innstalled). Thank You

title: Need help with uploading to arduino ng or older with atmega8

Answers: 0


body:
# Arduino UNO R3 Compatible Board ATmega328P ATmega16U2 #
http://www.ebay.in/itm/UNO-R3-ATmega328P-ATmega16U2-Compatible-Board-For-Arduino-with-USB-Cable-/201367107680?pt=LH_DefaultDomain_203&hash=item2ee26a3860
# Arduino UNO R3 ATmega328P USB Development Board CH340G
http://www.ebay.in/itm/UNO-R3-Development-Board-SMD-Chip-Arduino-Compatible-/301653217776?pt=LH_DefaultDomain_203&hash=item463beed1f0

### I will be working on a windows 7 32 bit pc.

title: What is the diffrence between following arduino boards and which should i buy?

Answers: 1

body:
The first is an unofficial clone of an R3 using the same schematic as the real R3.  The second is a rough copy using a cheaper USB serial interface chip.

Neither of them are real Arduino boards.  The first one is closer to the real UNO and should do the same things that a real UNO should do (assuming it works at all).  The second one - well, who knows?  You certainly can't do any of the fancy things to the USB interface that you can with a real UNO R3.

Which should you buy? Well, really, you shouldn't buy either of them - but if you *must* go for one I'd pick the first one.  Better to buy a real UNO from Arduino though, at least then you know what it is you're getting, and you expect it to work.  With these cheap Chinese clones (Chinduinos) you may just get a bunch of counterfeit chips selotaped to a piece of cardboard.


body:
I have a mpu6050(which I got from here http://www.sainsmart.com/sainsmart-mpu-6050-3-axis-gyroscope-module.html) and I have connected it to special ports on a sensor shield made for the mpu6050(http://www.amazon.co.uk/SainSmart-InstaBots-SS-SBR-1-0-Sensor-Shield/dp/B00N1YANH2) which is on a Arduino uno. I have a sketch which is meant to print stuff out to the serial monitor, however when the mpu6050 is attached nothing is printed out and when it is not attached the Arduino does print out things to the serial monitor. I attached other things to the sensor shield and things were printed out on the serial monitor, so I know it is the mpu6050 that is the problem.

This is my code

    #include <Wire.h>
    #include <SPI.h>
    #include <Mirf.h>
    #include <nRF24L01.h>
    #include <MirfHardwareSpiDriver.h>
    #include <I2Cdev.h>
    #include <MPU6050.h>

    MPU6050 accelgyro;
    int16_t ax, ay, az;
    int16_t gx, gy, gz;

    #define Gry_offset 0
    #define Gyr_Gain 0.00763358
    #define Angle_offset 4
    #define RMotor_offset 20
    #define LMotor_offset 20
    #define pi 3.14159

    long data;
    int x, y;
    float kp, ki, kd;
    float r_angle, omega;
    float f_angle;
    float Turn_Speed = 0, Turn_Speed_K = 0;
    float Run_Speed = 0, Run_Speed_K = 0, Run_Speed_T = 0;
    float LOutput,ROutput;

    unsigned long preTime = 0;
    float SampleTime = 0.08;
    unsigned long lastTime;
    float Input, Output;
    float errSum, dErr, error, lastErr;
    int timeChange;

    int TN1=3;
    int TN2=4;
    int ENA=9;

    int TN3=5;
    int TN4=6;
    int ENB=10;

    void setup() {
      Wire.begin();
      accelgyro.initialize();
      pinMode(TN1,OUTPUT);
      pinMode(TN2,OUTPUT);
      pinMode(TN3,OUTPUT);
      pinMode(TN4,OUTPUT);
      pinMode(ENA,OUTPUT);
      pinMode(ENB,OUTPUT);

      Mirf.spi = &MirfHardwareSpi;
      Mirf.init();
      Mirf.setRADDR((byte *)"serv1");
      Mirf.payload = sizeof(long);
      Mirf.config();
      Serial.begin(115200);
      Serial.print("Hello");
    }

    void loop() {
      Recive();
      accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
      r_angle = (atan2(ay, az) * 180 / pi + Angle_offset);
      omega =  Gyr_Gain * (gx +  Gry_offset);
      //Serial.print("  omega="); Serial.print(omega);
      if (abs(r_angle)<45){
        myPID();
        PWMControl();
      }
      else{
        analogWrite(ENA, 0);
        analogWrite(ENB, 0);
      }
    }

    void Recive(){
      if(!Mirf.isSending() && Mirf.dataReady()){
        Mirf.getData((byte *)&data);
        Mirf.rxFifoEmpty();

        y = data >> 16;
        x = data & 0x0000ffff;
        //Serial.print("  x="); Serial.print(x);
        //Serial.print("  y="); Serial.println(y);
        if(x >= 520){
          Run_Speed_K = map(x, 520, 1023, 0, 100);
          Run_Speed_K = Run_Speed_K / 50;
          Run_Speed = Run_Speed + Run_Speed_K;
        }
        else if(x <= 480){
          Run_Speed_K = map(x, 480, 0, 0, -100);
          Run_Speed_K = Run_Speed_K / 50;
          Run_Speed = Run_Speed + Run_Speed_K;
        }
        else{
          Run_Speed_K = 0;
        }
        if(y >= 520){
          Turn_Speed = map(y, 520, 1023, 0, 20);
        }
        else if(y <= 480){
          Turn_Speed = map(y,480,0,0,-20);
        }
        else{
          Turn_Speed = 0;
        }
      }
      else{
        x = y = 500;
      }
    }

    void myPID(){
      kp = analogRead(A0)*0.1;
      //kp=17;
      Serial.print("  kp=");Serial.print(kp);
      kd = analogRead(A2)*1.0;
      //kd=840;
      Serial.print("  kd=");Serial.print(kd);
      //ki = analogRead(A3)*0.001;  Serial.print("  ki=");Serial.print(ki);

      //kp = 0;  Serial.print("  kp=");Serial.print(kp);
      //kd = 0;  Serial.print("  kd=");Serial.print(kd);
      ki = 0.08;
      Serial.print("  ki=");Serial.print(ki);

      unsigned long now = millis();
      float dt = (now - preTime) / 1000.0;
      preTime = now;
      float K = 0.8;
      float A = K / (K + dt);
      f_angle = A * (f_angle + omega * dt) + (1 - A) * r_angle;

      Serial.print("  f_angle=");Serial.print(f_angle);

      timeChange = (now - lastTime);
      if(timeChange >= SampleTime){
        Input = f_angle;
        error = Input;
        errSum += error * timeChange;
        dErr = (error - lastErr) / timeChange;
        Output = kp * error + ki * errSum + kd * dErr;
        LOutput = Output + Run_Speed + Turn_Speed;  Serial.print("  LOutput=");Serial.print(LOutput);
        ROutput = Output + Run_Speed - Turn_Speed;  Serial.print("  ROutput=");Serial.println(ROutput);
        lastErr = error;
        lastTime = now;
      }
    }

    void PWMControl(){
      if(LOutput > 0){
        digitalWrite(TN1, HIGH);
        digitalWrite(TN2, LOW);
      }
      else if(LOutput < 0){
        digitalWrite(TN1, LOW);
        digitalWrite(TN2, HIGH);
      }
      else{
        digitalWrite(TN1, HIGH);
        digitalWrite(TN2, HIGH);
      }
      if(ROutput > 0){
        digitalWrite(TN3, HIGH);
        digitalWrite(TN4, LOW);
      }
      else if(ROutput < 0){
        digitalWrite(TN3, LOW);
        digitalWrite(TN4, HIGH);
      }
      else{
        digitalWrite(TN3, HIGH);
        digitalWrite(TN4, HIGH);
      }
        analogWrite(ENA, min(255, abs(LOutput) + LMotor_offset));
        analogWrite(ENB, min(255, abs(ROutput) + RMotor_offset));
    }

and this is a picture of the mpu6050 on the sensor shield

![enter image description here][1]

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

title: MPU6050 causing arduino not to run sketch

Answers: 1

body:
The shield you linked to is no longer sold.

The current version is
![enter image description here][1]

But it has no special connection for an MPU6050 breakout (and BTW that same 6050 board is $6 about everywhere else).  A shield serves no purpose for just the 6050 really.

If you connected the 6050 to the I2C lines (aka A4 & A5), Then you also need to connect an additional interrupt line.  If you are using unmodified example code, it depends on the interrupt being connected.

Here is a post made a while back using the 6050

[http://www.spiked3.com/very-cool-imu-demo/][2]

It is possible to use the 6050 without interrupts but you would have to (understand and) modify the standard example code.

Update: I knew you had a different board, and it had a connector for the 6050, the comment was that the link you provided, since it was 'no longer available', did not link to any documentation. Without a schematic it can not be known how it is hooked up beyond simple I2C. As you are using other devices I am not familiar with, I would expect some sort of conflict on the i2C bus maybe. Are all i2c bus devices using the same reference voltage? It does not matter if they are all 5v or all 3.3V as long as they are all the same.

Since you say 'nothing is printed' and your second line of setup is 'initialize' gyro, odds are good it is not getting past that. Simple (archaic) debugging, put a print (and a small delay) before and after the call to initialize.

My code uses the following for Wire.begin

    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
  Wire.begin();
  TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
  Fastwire::setup(400, true);
    #endif

I dont know if your Arduino is different and if it would make any difference.

I have a line after initialize

    mpu.testConnection();

That may or may not help you.

FYI PI is already defined, as is DEG_TO_RAD and RAD_TO_DEG

    if (abs(RAD_TO_DEG * headingDelta) > .1F)
  poseChanged = true;

Update: I just looked quickly at the code, and the only thing initialize does is write to i2c, it never waits really. And that means writing to I2C is hanging.  I ran into this once when I had an unpowered device on the bus. I thought it would not harm, but I was wrong.  Does the power light on the mpu come on? (is it really getting power?)  I have run them at 3.3v and 5V so I do not think that would be a problem, but  if you can, switch it to 3.3V to be sure. Getting down to the nitty gritty, you could check if the default pullup resistors are still on the board and did not get accidentally knocked off. Even better would be to try it with a known good MPU.  I have about 10 of them within reach :P (spiked3.com)

  [1]: https://i.stack.imgur.com/F7ccO.jpg
  [2]: http://www.spiked3.com/very-cool-imu-demo/


body:
I am interested in Arduino projects. I want to learn to develop my own Arduino based system. The problem is I am not sure which Adruino board must I start with. Any ideas are appreciated, I have searched many discussion forum but could not find a satisfactory answer.

My questions are:

1. Which Arduino Board should I start with?
2. Is it possible to work on Arduino based projects without the board; like having a simulation of the board? If so how?

Answers: 2

body:
Depending on your budget you could start with an Arduino Uno starter kit that will include the Arduino, breadboard and wires plus different sensors (like [this one](http://www.amazon.com/The-Ultimate-Kit-Arduino-oddWires/dp/B00K6PYGQ8) - but there are others with less peripherals and cheaper).

If you have a lower budget you can still buy the arduino and many separate sensors/LEDs etc from eBay.

By googling you'll find a lot of tutorials about getting started with the hardware that you bought.

body:
My advice:
 - get a model with USB port (some do not have one)
 - the DUE might seem attractive, but you have less libraries available and less examples, I'd recommend it more as follow up
 - you will get frustrated if you do not know how to code, at least a bit, so if you have not programmed before, you might want to spend some time trying simple stuff just with your PC
 - same about electronics: if you do not have previous experience, it might be preferable to play a bit with a breadboard and some components (LEDs, resistors, switches, etc.); this will reduce the likelyhood that you fry your Arduino. Remember to buy some cables MM/MF/FF, you will end up needing all of them, sooner or later. For powering the board, you can find nice power supplies that cn be powered by a USB cable.

I have bought UNOR3 clones at $4-$5 on ebay, so if you can afford it, I'd suggest you buy a couple, that will enable you playing with I2C master slave and similar configurations.


body:
I'm looking for some method to control an Arduino with voice commands.

Could this work on this platform?

title: Can we control an Arduino with voice commands?

Answers: 1

body:
Yes possible on some of the high end Arduinos, but I know of no example where it has been done. The quality of recognition will be proportional to the processing power provided. In the case of an Arduino, probably not at an acceptable level.

You would be much better off looking at the multitudes of PC solutions, and using the Arduino as an interface to what ever it is you plan on controlling.

FYI: [https://www.sparkfun.com/products/13316][1]

  [1]: https://www.sparkfun.com/products/13316


body:
Is it possible to "send" a serial command to the device itself to see the response?
I have written a little routine based on a couple of serial sends and receives and want to see if that works out like I want.

EDIT:

I have a device (an AVR with arduino boot loader) and as part of my program, the device exchanges phrases with peripheral devices over a serial connection. Since I have right now just the arduino itself and can't really test, if at least the logic behind the serial part of works out, I would like to get serial commands from somewhere and trigger 'continuous talking', so I want to monitor the response behavior of my module, if it gets a certain command (stability reasons). Instead of waiting for a second device, is it possible to "link the TX/RX line to itself" internally or externally to test my program with itself?

title: Sending serial commands to yourself

Answers: 1

body:
Yes, you can do that by cross-connecting the transmit and receive pins on the Arduino. But then your devices sits there silently murmuring to itself (or not...) and you can't really tell what it's saying, or if it's doing anything unless you can observe some other hardware - LEDs, a 'scope, f/ex.

But why not hand-type or script some messages to it on your PC? If the Arduino sketch would make some brief, coherent replies you could confirm what it's doing and debug it if necessary.

I've done just this in your situation: Two of us defined a serial protocol - the ASCII (for human readability!) commands and replies that either end could make or expect. Then each of us wrote the communication code for one of the two devices and proved that it met the protocol. Once both of us had finished and were confident in our respected communication code, we plugged the two devices together, and - they played! Nicely! :)  And if they hadn't we could have eavesdropped on the serial line and printed their attempted conversation to discover where it went wrong.


body:
I'm trying to read 5 analog inputs, but all the pins are reading the same as pin A0, plus or minus a couple points. I tried using pulldown resistors on all 5 pins and it made no difference. The board is a Leonardo. Thanks for any ideas/help!

    void setup() {
        Serial.begin(115200);
        analogReference(EXTERNAL);
    }

    void loop() {
        int A0, A1,A2,A3,A4;
        delay(200);
        A0= analogRead(A0);
        A1= analogRead(A1);
        A2= analogRead(A2);
        A3= analogRead(A3);
        A4= analogRead(A4);

        Serial.print(A0);
        Serial.print(" ");
        Serial.print(A1);
        Serial.print(" ");
        Serial.print(A2);
        Serial.print(" ");
        Serial.print(A3);
        Serial.print(" ");
        Serial.print(A4);
        Serial.print("\n");
    }

title: Analog pins all reading same value

Answers: 1

body:
>     int A0, A1,A2,A3,A4;
    delay(200);
    A0= analogRead(A0);
    A1= analogRead(A1);
    A2= analogRead(A2);
    A3= analogRead(A3);
    A4= analogRead(A4);

Your local variables (`A0` through `A4`) are shadowing the global variables for the pins (`A0` through `A4`). Give your local variables different names.


body:
I just want to confirm something before I wire up my first ever Arduino project and fry all the stuff I just spent money on.

It is my *understanding* that the `Vin` power input will tolerate a 9V battery and use voltage regulators to pare it down to either 3.3V or 5V (as different parts of the board require). So it is then my *assumption* that if I have a 9V battery running to `Vin`, that I could then connect a power wire to the `3.3V` connector, and reliably get a 3.3V signal (and ditto for 5V), **yes?**

Or, is it that they are *input* jacks *expecting* either 3.3V or 5V signals? I guess I'm confused over this:

* Will `Vin` then power the 3.3V and 5V inputs, giving me access to voltage at that level; or
* Do I have to choose between 3.3V, 5V or `Vin`, and only use one of those to power my board (with the appropriate voltage level)

title: Arduino Due and Vin, 3.3V and 5V power inputs

Answers: 2

body: Yes your assumption is correct you can power 3.3v and 5v items from those pins as long as you don't take more current than the onboard regulator(s) can supply

body:
`DC Jack` is connected, through a diode, to `Vin`.

`Vin` is stepped down to `5V` on-board.

`5V` is stepped down to `3V3` on board.

Thus you can do any one of the following numbered items.

 1. Connect a 7-12V supply to the `DC Jack`; thus:
- use `Vin` as a supply @ DC - 0.7V for off-board peripherals, and
- use `5V` as a supply for off-board peripherals, and
- use `3V3` as a supply for off-board peripherals.

 2. Connect a 6-12V supply to `Vin`; thus:
- use `5V` as a supply for off-board peripherals, and
- use `3V3` as a supply for off-board peripherals.

 3. Connect 5V supply to the `5V`; thus:
- use `3V3` as a supply for off-board peripherals.

The above is only guaranteed for boards that **follow the reference schematic**, as plenty of clone/compatible boards do. If you buy a cheap Chinarduino and something doesn't work, or the thing breaks, after following anything above then that's your tough luck.


body:
I am trying to understand what each pin on my Arduino Due is and what it is used for, and so I have been searching for things like "*Arduino Due pinout*", "*Arduino Due pin mapping*" and similar.

The best I could find was [this table](http://www.arduino.cc/en/Hacking/PinMappingSAM3X), however it doesn't help you out at all if you are completely new to electronics and have no idea what `TX2`, `SDA` or `NPCSO` mean, etc.

Does anybody know of Arduino/Due documentation that explains what each I/O pin is?

title: Arduino Due Pinout with Explanations?

Answers: 1

body:
The Arduino Due is backed by an Atmel SAM3X8E ARM Cortex-M3 microprocessor and most of the pins on the Due are connected directly to this chip. Therefore, you can refer directly to the chip's datasheet for descriptions of these hardware features.

[Atmel SAM3X8E ARM Cortex-M3 datasheet][1]

  [1]: http://www.atmel.com/Images/Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf


body:
I'm trying to create a code using an Arduino Uno board to increment and decrement the output voltage of the Arduino Uno which is 5 volts and I need to step it up to 10 volts which I have done below.

The things that are missing on the schematic are two buttons. I want to be able to increment 0.5 volts with each press of Button-A until the Arduino is at 5 volts. With Button-B I want to be able to lower the voltage by 0.5 volts with each press of the button till value is 0.

I can do the calculations and the circuit design but I'm not much of a programmer. I just want to know if anyone can point me in a good direction of where I can get the right code. I have already looked at all the tutorials on the Arduino Website. I do know I have to work with the PWM functions as well as `attachinterrupt()` and `Debounce()` functions. Also, how do I set the increments so that I don't go over, say it takes 10 presses to get to 5 volts on the 11th press have it not do anything so I don't break anything. So can anyone please help me with any suggestions?

I have a low pass filter on the circuit for noise handling and like I said I need to add in the buttons to my schematic.

![schematic](https://i.stack.imgur.com/sMiDk.png)

Here is my code I have made. I'm using an LED to test the Vout aspect. So far I can only get my LED to flicker from 2 to 4 volts and my buttons A and B don't work. Can someone look over my code and see how bad I made this?

    int PWMPin = 6; // output pin supporting PWM
    int buttonApin = 9; // buttonA to pin 9 PWM
    int buttonBpin = 10; // buttonB to pin 10 PWM
    float value = 0; // read the value at 0
    int fadeValue = value;

    void setup()
    {
      Serial.begin(9600); //initialize serial communication at 9600 baud
      pinMode(buttonApin, INPUT_PULLUP);
      pinMode(buttonBpin, INPUT_PULLUP);
      pinMode(PWMPin, OUTPUT);
    }
    void loop()
    {
      {
        int port = analogRead(0);
        port = map(port, 0, 10, 0, 255);
        analogWrite(6, port);
      }

      {
      if (digitalRead(buttonApin) == LOW, fadeValue)
      {
      // fade from min to max in increments of 25.5 points: basically (0.5 volts)
      for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=25.5)

        digitalWrite(PWMPin, fadeValue);

        // sets the value (range from 0 to 255):
       Serial.println(PWMPin);
       analogWrite(PWMPin, fadeValue);
      }
      }

      {
        if (digitalRead(buttonBpin) == LOW, fadeValue)
      {
      // fade from max to min in increments of 25.5 points:
      for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=25.5)

        digitalWrite(PWMPin, fadeValue);

      // sets the value (range from 0 to 255): basically (0.5 volts)
      analogWrite(PWMPin, fadeValue);
      }
      }
    }

title: How to increment and decrement an output voltage by using two buttons?

Answers: 2

body:
If all you have to do is to read those 2 buttons, you could just forgo the interrupts and simply poll in the main loop.
The [Bounce2 library][1] does basically the same.

Also, about the PWM, why not an R-2R?

10V/0.5V + 1 => 21 steps < 32 => 5 bits => 6 resistors.

But it could be more precise, as you would not depend on the oscillator, rather on the precision of the resistors.

  [1]: http://playground.arduino.cc/Code/Bounce

body:
<!-- language-all: lang-C++ -->

I suggest you to use debounce to detect if a pin has been definitely pressed. You could also test using interrupts (hint: interrupts can happen multiple times even if you "only" pressed once). So either use Arduino's example of debounce or take a look at the [Bounce2 library][1] found on their website.

Now that you can check whether or not either button A or B has been pressed, how do you keep track of the voltage to be output? You should use a `counter` variable that will be incremented when button A is pressed and decremented when button B is pressed. Here is a pseudocode:

    if(ButtonA == pressed)
      counter++;
    else if(ButtonB == pressed)
      counter--;

This `counter` variable can be used to control the output voltage. Remember that the argument for `analogWrite()` function on the Arduino Uno is the duty cycle which takes in values from 0 to 255. So `analogWrite(0)` ≣ 0 Volt and `analogWrite(255)` ≣ 5 Volt. So at the moment, you couldn't just do `analogWrite(counter)` because you would need to press 255 times button A!

Instead, you would need a way to convert your counter to reflect the increment you need. You mentioned that it should require 10 presses to reach 5 Volt at the Arduino output, and the easiest way to accomplish this is to use Arduino's [Map function][2]. The pseudocode would look like this:

    Output = map(counter, 0, 10, 0, 255);
    analogWrite(Output);

Now there is one last step! The map function will limit the output voltage from 0 to 5 Volt so everything will be safe; however, the counter is not limited to 0 to 10. This means that even if the counter is at 15 (because you pressed button A too many times) the voltage will be 5 Volt and you would need to press button B at least 6 times to see the voltage go down! So to limit the counter you could easily implement your own function:

    if(counter >= 10)
      counter = 10;
    else if (counter<= 0)
      counter = 0;

You could also use Arduino's `constrain()` function which more information can be found on their website.

Hopefully this points you in the right direction.

  [1]: http://playground.arduino.cc/Code/Bounce
  [2]: http://www.arduino.cc/en/Reference/Map


body:
Hey I just started using arduino and so far can't get any help with how to write a code for an led to turn on when someone gets in range of a three pin ultrasonic sensor, and off when they are out of a specific range.

Any help?

title: how to make an led turn on when something gets close to an ultrasonic sensor

Answers: 1

body:
Try with this and check that at least you can reproduce the desired effect:
http://www.arduino.cc/en/Tutorial/Ping?from=Tutorial.UltrasoundSensor

Then you can refer to this for the part related to driving the LED:
http://www.arduino.cc/en/Tutorial/Blink?from=Tutorial.BlinkingLED

Since the ultra sound demo already calculates the distance, you can do the test on that to decide when to turn ON/OFF the LED.


body:
I am trying to connect my Arduino Uno board with SeeedStudio Can Bus Shield to my 2006 325i BMW. After compiling and uploading the example program by SeeedStudio, the serial monitor returns "Can Bus Shield Init ok!"

<!-- language: lang-c -->

    // demo: CAN-BUS Shield, receive data with check mode
    // send data coming to fast, such as less than 10ms, you can use this way
    // loovee, 2014-6-13

    #include <SPI.h>
    #include "mcp_can.h"

    // the cs pin of the version after v1.1 is default to D9
    // v0.9b and v1.0 is default D10
    const int SPI_CS_PIN = 9;

    MCP_CAN CAN(SPI_CS_PIN); // Set CS pin

    void setup() {
      Serial.begin(115200);
    START_INIT:
      if(CAN_OK == CAN.begin(CAN_500KBPS)) {
      // init can bus : baudrate = 500k
        Serial.println("CAN BUS Shield init ok!");
      } else {
        Serial.println("CAN BUS Shield init fail");
        Serial.println("Init CAN BUS Shield again");
        delay(100);
        goto START_INIT;
      }
    }

    void loop(){
      unsigned char len = 0;
      unsigned char buf[8];
      if(CAN_MSGAVAIL == CAN.checkReceive()) {
        // check if data coming
        CAN.readMsgBuf(&len, buf);
        // read data,  len: data length, buf: data buf
        unsigned char canId = CAN.getCanId();
        Serial.println("-----------------------------");
        Serial.println("get data from ID: ");
        Serial.println(canId);
        for(int i = 0; i<len; i++) {
          // print the data
          Serial.print(buf[i]);
          Serial.print("\t");
        }
        Serial.println();
      }
    }

So I get the initialize statement returned but I'm not receiving any data. It seems like the `if(CAN_MSGAVAIL == CAN.checkReceive())` statement isn't executed. I found my vehicle's Can high and Can low wires and inserted them into my Can Bus Shield. So I'm not sure if it's a code problem or if the wires aren't transmitting the data to the shield. Any help would be great.

title: Can Bus Shield Not Receiving Data

Answers: 2

body:
It may be a dumb question, but are you sure your car CAN bus is 500kbps?
Have a look at this:
[pdfLink](http://share.qclt.com/bmw资料/Bus & Power/BUS _en.pdf)
Maybe try different speeds? 100kbps maybe?

Also, look at the schematics of your shield? Is the bus termination resistor soldered on the board?

body:
Make sure to cut the P1 trace (see the link below) and also to connect GND from the OBD-2 to the shield/Arduino. There are two ground pins on the OBD-2 port, Signal and Chassis Ground. I went with Signal GND, but allegedly they are linked anyways.

This [guide][1] helped me a lot.

  [1]: http://matthewcmcmillan.blogspot.cz/2013/10/arduino-sending-data-over-can-bus.html


body:
I am busy toying with some PIR sensors to detect movement etc for a nightlight for my kids. One of the sensors I ordered is the PYM-1 PIR sensor.

The data sheet states the following:

 - Operating Voltage: 4,5~5V.
 - Standby current: 65 micro-amps (65uA)
 - Operating Current: 40mA (40 milli-amps)

The limit for current on the arduino pins is 40mA. According to documentation at the arduino site 40mA is the upper limit per pin and the site clearly states: Absolute Maximum Ratings - the point where damage will start to happen I would rather avoid sinking the current directly on the Arduino.

So my question is will sinking 40mA on a pin cause damage? I have not been visited by the blue smoke genie yet and would rather avoid it at this point.

I suspect it might be safer to run this via a transistor and external power than directly on the arduino?

title: PYM-1 PIR sensor current concerns

Answers: 2

body:
When I look at the PYM-1 seen here:

http://www.ebay.com/itm/Infrared-PIR-Human-Sensor-NEW-Arrival-Pyroelectric-DIY-Kit-PYM-1-for-Arduino-/271677900953

I don't see any need for an external microprocessor such as an Arduino.  It seems that one just applies 5V as input and it switches on/off up to 300W of power.  Where would one use an Arduino GPIO?

body:
This is completely acceptable for your intended purpose.

By itself it will act as a light on/off trigger as others have noted.
An Arduino could be added if you wish to add extra features when the PIR is triggered. In it's most basic light-switching form using an Arduino is overkill.

By itself it will act as a light on/off trigger as others have noted.
An Arduino could be added if you wish to add extra features when the PIR is triggered. In it's most basic light-switching form adding an Arduino is overkill.

When it comes to playing overkill can be good :-)

________________________

**To use it to provide input to an Arduino and NOT to a mains level light:**

**NB** relay contacts may only be connected to mains for light switching **OR** to the Arduino. **NEVER** to both at the same time.

Connect it's DC supply input to your Arduino (or other) power supply.
As long as the **supply** can provide 40 mA when needed it will work OK.
40 mA is a **power supply** rating This is unrelated to the Arduino pin loading.

Connect the output to an Arduino digital pin configured as an input.

![enter image description here][1]

The output is a relay, activated when an object is sensed.
When inactive the centre pin is probably connected to the right pin - Check with Ohm meter.

When activated the left pin in connected to the centre pin (see their diagram)

Connect ground to right pin.
Connect Arduino digital input to centre pin.
Connect a "high" level to left hand pin.
OR as Majenko suggests, just set the pin to have pullups enabled.

If connecting to V+ as shown then V+ can be Vcc  (=5V for a 5V Arduino, 3v3 for a 3V3 Arduino)
DO NOT set V+ to higher than Arduino's Vcc.
You can connect a say 1k to 10k resistor from V+ to the voltage source bur still do not set V+ above Vcc.
OK - just have pullups enabled:-)

eg (untested)

> int ADCMode = 0;
 int PIRPin = 6;                 // PIR connected to digital pin 6
 void setup()
 {
   pinMode(PIRPin, INPUT_PULLUP); // set PIRpin as input with pullup
 }
 void loop()
 {
  ...
   ADCMode  = digitalRead(PIRpin);   // $Read PIR status
 ...
 }

When the circuit activates digitalRead() will return a high.
When the circuit is not activated digitalRead() will return a low.

__________________

See [here](http://www.arduino.cc/en/Tutorial/DigitalPins) re Arduino pin modes

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


body:
I have connected Arduino with ESP8266 with

Arduino pin 2 connected to ESP's Tx Arduino pin 3 connected to ESP's Rx via Voltage Divider Arduino GND connected to ESP's GND Arduino 3v3 connected to ESP's CH_PD

I have powered ESP8266 using 1117 Voltage regulator

When I initially bought ESP8266 it was working properly(I could even set up a server) but now when I connect it to Arduino an endless stream of garbage values is seen on the Serial Monitor...

The arduino is programmed with the following code

    #include <SoftwareSerial.h>

    SoftwareSerial esp8266(2,3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                                 // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                                 // and the RX line from the esp to the Arduino's pin 3
    void setup()
    {
      Serial.begin(9600);
      esp8266.begin(9600); // your esp's baud rate might be different
    }

    void loop()
    {
      if(esp8266.available()) // check if the esp is sending a message
      {
        while(esp8266.available())
        {
          // The esp has data so display its output to the serial window
          char c = esp8266.read(); // read the next character.
          Serial.write(c);
        }
      }

      if(Serial.available())
      {
        // the following delay is required because otherwise the arduino will read the first letter of the command but not the rest
        // In other words without the delay if you use AT+RST, for example, the Arduino will read the letter A send it, then read the rest and send it
        // but we want to send everything at the same time.
        delay(1000);

        String command="";

        while(Serial.available()) // read the command character by character
        {
            // read one character
          command+=(char)Serial.read();
        }
        esp8266.println(command); // send the read character to the esp8266
      }
    }

title: ESP8266 and Arduino Interfacing

Answers: 1

body:
There is a new command for the ESP8266 in AT version:0.50.0.0 - SDK version:1.4.0 that lets you explicitly set the full UART configuration:

`AT+UART_CUR` – set the current UART configuration
This command sets the current UART configuration; it does not write to the flash. Hence there is no change in the default baud rate.

For example:

`AT+UART_CUR=9600,8,1,0,0`


body:
I need some help. I use function rx_setup()  оf library VirtualWire.h which is used to transmit information wirelessly. The function use timer аnd there is  conflict with any of the other libraries. Does anyone know how I can change the timer, which uses function?

This is the function:

    void vw_setup(uint16_t speed)
    {
        uint16_t nticks; // number of prescaled ticks needed
        uint8_t prescaler; // Bit values for CS0[2:0]

    #ifdef __AVR_ATtiny85__
        // figure out prescaler value and counter match value
        prescaler = _timer_calc(speed, (uint8_t)-1, &nticks);
        if (!prescaler)
        {
            return; // fault
        }

        TCCR0A = 0;
        TCCR0A = _BV(WGM01); // Turn on CTC mode / Output Compare pins disconnected

        // convert prescaler index to TCCRnB prescaler bits CS00, CS01, CS02
        TCCR0B = 0;
        TCCR0B = prescaler; // set CS00, CS01, CS02 (other bits not needed)

        // Number of ticks to count before firing interrupt
        OCR0A = uint8_t(nticks);

        // Set mask to fire interrupt when OCF0A bit is set in TIFR0
        TIMSK |= _BV(OCIE0A);

    #elif defined(__arm__) && defined(CORE_TEENSY)
        // on Teensy 3.0 (32 bit ARM), use an interval timer
        IntervalTimer *t = new IntervalTimer();
        t->begin(TIMER1_COMPA_vect, 125000.0 / (float)(speed));

    #else // ARDUINO
        // This is the path for most Arduinos
        // figure out prescaler value and counter match value
        prescaler = _timer_calc(speed, (uint16_t)-1, &nticks);
        if (!prescaler)
        {
            return; // fault
        }

        TCCR1A = 0; // Output Compare pins disconnected
        TCCR1B = _BV(WGM12); // Turn on CTC mode

        // convert prescaler index to TCCRnB prescaler bits CS10, CS11, CS12
        TCCR1B |= prescaler;

        // Caution: special procedures for setting 16 bit regs
        // is handled by the compiler
        OCR1A = nticks;
        // Enable interrupt
    #ifdef TIMSK1
        // atmega168
        TIMSK1 |= _BV(OCIE1A);
    #else
        // others
        TIMSK |= _BV(OCIE1A);
    #endif // TIMSK1

    #endif // __AVR_ATtiny85__

        // Set up digital IO pins
        pinMode(vw_tx_pin, OUTPUT);
        pinMode(vw_rx_pin, INPUT);
        pinMode(vw_ptt_pin, OUTPUT);
        digitalWrite(vw_ptt_pin, vw_ptt_inverted);
    }

    #endif // ARDUINO

    // Start the transmitter, call when the tx buffer is ready to go and vw_tx_len is
    // set to the total number of symbols to send

title: Rf receiver, change timer

Answers: 0


body:
I'm working on my project car, and I have decided I would like to have a GPS and log some sensors too. I'm just at a bottle neck here, the sensors I have brought pull about 7v each where I can't pull that much from the breakout board that I have, and I can't seam to get the GPS to work.

I've tried using ths code but software serial isn't supported on the edison:

    // GPS Setup
    #define rxGPS 0
    #define txGPS 1
    SoftwareSerial serialGPS = SoftwareSerial(rxGPS, txGPS);
    String stringGPS = "";

    void setup() {
      pinMode(rxGPS, INPUT);
      pinMode(txGPS, OUTPUT);

      Serial.begin(9600);
      Serial.println("Started");

      // GPS Setup
      serialGPS.begin(4800);
      digitalWrite(txGPS,HIGH);

      // Cut first gibberish
      while(serialGPS.available())
        if (serialGPS.read() == '\r')
          break;
    }

    void loop()
    {
      String s = checkGPS();
      if(s && s.substring(0, 6) == "$GPGGA")
      {
        Serial.println(s);
      }
    }

    // Check GPS and returns string if full line recorded, else false
    String checkGPS()
    {
      if (serialGPS.available())
      {
        char c = serialGPS.read();
        if (c != '\n' && c != '\r')
        {
          stringGPS  = c;
        }
        else
        {
          if (stringGPS != "")
          {
            String tmp = stringGPS;
            stringGPS = "";
            return tmp;
          }
        }
      }
      return false;
    }

Any ideas or help would be much appreciated

title: GPS logging on the intel edison breakout board

Answers: 2

body:
Try this:

    String GPSLine;

    bool checkGPS()
    {
      while(serialGPS.available())
      {
        char c = serialGPS.read();
        if(c == '\n') return true;
        if(c == '\r') continue;

        GPSLine += c;
      }
      return false;
    }

    void loop()
    {
      if(checkGPS())
      {
        Serial.println(GPSLine);
        GPSLine = "";
      }
    }

body:
You might try my [NeoGPS](https://github.com/SlashDevin/NeoGPS) library.  It has a diagostic program and some good information in the [Troubleshooting section](https://github.com/SlashDevin/NeoGPS/blob/master/doc/Troubleshooting.md).  And NeoGPS doesn't use the `String` class, although you can safely waste lots of RAM on the Edison.  :P

For an Edison build, you may have to change the PACKED_DATA configuration item, described [here](https://github.com/SlashDevin/NeoGPS/blob/master/doc/Configurations.md#platforms).

(This is an Arduino product, right?)


body: I'm using an Arduino to control a reverse osmosis machine, I would like after a certain number low pressure events to return to the testing routine. Can you call to previous functions?

title: How do you call to a previous function?

Answers: 2

body:
What do you mean by "previous"? In the call stack or in the code?
Either way, you can call any (public|member|static) function you want at any time, even call the very same function you're already in (recursion, but not recommended on Arduino or any other embedded system).

body:
You need to get your head around the Finite State Machine (FSM).

It is a programming method which allows your program ("Machine") to be in any of a certain number ("Finite") of states ("State").  One state would be reading pressure. Another state would be "testing", or whatever.

I wrote a tutorial ages ago about it: http://hacking.majenko.co.uk/finite-state-machine


body:
I have a brand new 8GB micro SD card freshly formatted as FAT in my Yun.

When I run `df -h`, I don't see the card's capacity included.
When I enter `cd /mnt/sda1`, it says `can't cd to /mnt/sda1`.

When I SSH into the Yun with `ssh root@arduino.local` and run `dmesg`, I see confirmation that the SD card is recognized:

    [   11.510000] sd 0:0:0:0: [sda] 15431680 512-byte logical blocks: (7.90 GB/7.35 GiB)
    [   11.510000] sd 0:0:0:0: [sda] Write Protect is off
    [   11.510000] sd 0:0:0:0: [sda] Mode Sense: 03 00 00 00
    [   11.510000] sd 0:0:0:0: [sda] No Caching mode page present
    [   11.510000] sd 0:0:0:0: [sda] Assuming drive cache: write through
    [   11.520000] sd 0:0:0:0: [sda] No Caching mode page present
    [   11.520000] sd 0:0:0:0: [sda] Assuming drive cache: write through
    [   11.530000]  sda: sda1
    [   11.530000] sd 0:0:0:0: [sda] No Caching mode page present
    [   11.530000] sd 0:0:0:0: [sda] Assuming drive cache: write through
    [   11.540000] sd 0:0:0:0: [sda] Attached SCSI removable disk

How can I access my SD card and include it in the Yun's recognized storage space?

title: Cannot access SD card on Yun

Answers: 0


body:
Using an ILI9341. I'm trying to set the rotation from within a class, but it's not working.  The code is very straight forward.

If I rotate in the class, the setRotation code does not work but the text is still printed. The pointer is set properly and the text is still printed, it just doesn't get rotated.

Outside of the class, the rotation works fine.

Any help would be greatly appreciated!

    #include "SPI.h"
    #include "Adafruit_GFX.h"
    #include "Adafruit_ILI9341.h"

    #define TFT_DC 5
    #define TFT_CS 3

    Adafruit_ILI9341 *tft;
    uint8_t newRotationAngle = 0;

    void drawStuff() {
        tft->setTextColor(map(rand(), 0, RAND_MAX, 0, 0xffff));
        tft->fillRect(0, 0, tft->width(), tft->height(), ILI9341_BLACK);
        tft->setCursor(0, 0);

        tft->print(F("01234567890"));
        delay(250);
    }

    class test {
    public:
        void init(Adafruit_GFX *_p) { ptrTft = _p; };

        void inClassRotation(int newRotation) {
            ptrTft->setRotation(newRotation);
            drawStuffInClass();
        };

        void drawStuffInClass() {
            ptrTft->setTextColor(map(rand(), 0, RAND_MAX, 0, 0xffff));
            ptrTft->fillRect(0, 0, ptrTft->width(), ptrTft->height(), ILI9341_BLACK);
            ptrTft->setCursor(0, 0);

            ptrTft->print(F("01234567890"));
            delay(250);
        }

        Adafruit_GFX *ptrTft;
    };

    test instance;

    void setup() {
        tft = new Adafruit_ILI9341(TFT_CS, TFT_DC);

        tft->begin();
        tft->setTextSize(2);

        instance.init(tft);
    }

    void outsideClassRotation(Adafruit_GFX *passed) {
        passed->setRotation(newRotationAngle);
        drawStuff();
    }

    void loop(void) {
        newRotationAngle++;

        // This works. No problems.
    //    outsideClassRotation(tft);

        // This does NOT rotate but still prints the text fine.
        instance.inClassRotation(newRotationAngle);

    }

title: Adafruit_GFX setRotation not working when called from within a class

Answers: 1

body:
I would actually be quite surprised if `outsideClassRotation()` actually
worked. My guess is that _it does not work as is_. Maybe it did work at
some point, but then you made some subtle changes to your code and did
not check that it is still working.

Here is the deal: there are two `setRotation()` methods:

- `Adafruit_GFX::setRotation(unsigned char)` does very little besides
  storing the rotation angle... which is not used anyway.
- `Adafruit_ILI9341::setRotation(unsigned char)` actually sends commands
  to the LCD asking it to apply the rotation; this is the method you
  want.

The problem is that _these methods are not `virtual`_, which means that
when you call them through a pointer, as in
`some_pointer->setRotation(the_angle);`, you get the method
corresponding to _the type of the pointer_, not the type of the actual
object. For example:

<!-- language: lang-c++ -->

    tft->setRotation(the_angle);     // calls Adafruit_ILI9341::setRotation()
    ptrTft->setRotation(the_angle);  // calls Adafruit_GFX::setRotation()
    passed->setRotation(the_angle);  // calls Adafruit_GFX::setRotation()

I checked this by uncommenting your call to `outsideClassRotation()` and
disassembling the compiled binary: both times you are calling
`Adafruit_GFX::setRotation()`.

**Solution**: change your `Adafruit_GFX *` pointers to be of
type `Adafruit_ILI9341 *`, or patch Adafruit\_GFX.h to make
`setRotation()` virtual.


body:
I'm transmitting: Temperature: 28.22C

and on the receiving end I'm receiving the whole tranmission as a string. I'm trying to spilt Temperature to leave it as a string and 28.22 as a float to compare, how do I do that ?

TX end hardware: (Arduino Uno board with Xbee S1)  to computer
RX end hardware: (Arduino Uno board with Xbee S2)  to computer

title: Spilt string and convert to float to compare

Answers: 2

body:
I suppose your communication is working... In order to retrieve a floating number from a string you might use toFloat() function. You can watch the reference page [here][1] to understand how does it work.

  [1]: http://www.arduino.cc/en/Reference/StringToFloat

body:
Okk very simple approach :-

Suppose this is your string variable inStr = "Temperature: 28.22C"

    String inStr = "Temperature: 28.22C";
    int indexOfSpace = inStr.indexOf(' ');
    //this stores the address of the space character in the string.
    int indexOfC = inStr.indexOf('C');

    String Temp = inStr.substring(indexOfScace+1,indexOfC);
    //as the parameter for the function is supposed to be the starting point of the string to
     be extracted and one more than its ending point.

    //Now to convert to float

    float TempFlo = Temp.toFloat();


body:
I flashed my ESP-01 with the [nodemcu firmware 512k version][1], and everything was working fine.  I testing some lua scripting on init.lua and it was working.  Then, after writing a bunch of code and uploading, the module restarted.  And it restarted.  And it's still restarting, over and over again, and prints to serial

    CÀbc0°ýbcü¨HøNodeMcu 0.9.4 build 20141230  powered by Lua 5.1.4
    ö,3bþÈH

It was always printing the garbage in there before, so I'm not worried about that.  However, I can't send anything to the device--I can't send serial commands, or reflash the device.  I'm thinking I overloaded the memory or something.  Anyone have any ideas for recovering this brick?

  [1]: https://github.com/nodemcu/nodemcu-firmware

title: esp8266 esp-01 crashing, restarting over and over

Answers: 1

body:
Turns out I was pulling up on the GPIO0 pin, instead of down.  Ensure you have the correct pin-out when flashing.

ESP-01 VCC - 3.3v Serial Adapter
ESP-01 GND - Ground or Minus Serial Adapter
ESP-01 RX - Connect to TX on Serial Adapter
ESP-01 TX - Connect to RX on Serial Adapter
ESP-01 CH_PD - 3.3v Serial Adapter
ESP-01 GPIO0 - Pull low by connecting to ground / minus

There also seems to be a problem with NodeMCU not clearing variables in the Ram, so Ram fills up as you run, and this causes the module to crash upon restarting, over and over.  That is also what was happening.  There is some problem with wifi.sta.getap() that exacerbates this.


body:
I am doing a project with bi-color led matrix 8x8 and MAX7219 as the LED driver. I want to implement a fading effect on the LEDs, like mixing the two colors by varying the individual duty cycles.

My idea is the use of the `Iset` parameter; I would connect the PWM pin from Arduino through the `Rset` resistor and feed that into the Iset of the MAX7129 instead of 5V supply. Please suggest whether or not this is possible, if not what can be the alternative approach?

title: Fading the brightness of LEDs using MAX7219 and PWM

Answers: 1

body:
This is possible in two ways:

 1. The MAX72xx has its own internal intensity control register. From the datasheet:

> Digital control of display brightness is provided by an internal pulse-width modulator [...]. The modulator scales the average segment current in 16 steps from a maximum of 31/32 down to 1/32 of the peak current set by RSET [...].

This of course requires no extra components or effort, but you are limited slightly by only a 4-bit intensity resolution. Also, there is no 'off' so you'd have to either manually blank the displays or put the ICs into shutdown mode.

 2. Your suggested way is possible. However, the low frequency of the Arduino's PWM may lead to flickering if the MAX7219's internal segment current reference driver needs a steady voltage. You'll have to consider smoothing the PWM output through a low pass filter - the TL072/TL082 has two op-amps so you can use one for colour A and the other for colour B. I'd choose an op-amp over passive filtering because the current drawn from the Arduino will be negligible and the stability of the current into the MAX7219 will be improved.


body:
This is my first circuit ever (!) and so I'm hoping that I'm just making an easy-to-spot rookie mistake. I am trying to power an Arduino Due with a 9V battery and then have the Due in turn power a red LED. No blinking. No sketchpad/C program flashed to the chip. Just straight up electricity:

![enter image description here][1]

When I connect the battery, several things happen:

 1. There is a green power LED on the Due that lights up; and
 2. Right next to it is an orange LED (on the Due itself) that blinks every few seconds (not sure what this LED is or what the blinking means, but providing that detail for good measure); and
 3. The red LED on the breadboarrd does **not** light up

This is a 2V/15mA LED, and as you can see I'm powering it from the 5V power jack on the Due. So a 220 ohm resistor should be perfect for it (`R = (Vs - V) / I = (5V-2V) / .015A ~= 220 ohms`).

So, for the first time ever, I busted out my multimeter, set it to the voltage setting, and started testing the circuit. First I tested `Vin` and `GND` on the Due (that is, the connection between the battery and the Due), and the multimeter lit up and hovered (correctly) around 5V. So far so good. Next I tested the power and ground connections on the breadboard power rails (indicated in green above). Again, the multimeter reported a roughly 5V power supply. Then I tested the connection from the power rail to the row (purple in pic above) feeding power to the resistor, and to my surprise, the multimeter reports **no power** at those two purple locations.

My *understanding* was that the power rail will power the entire column its connected to (in my case, the left-most column), and then any rows connecting to a power rail/column will also be powered. So I'm not understanding why there's voltage on my power rail/column, but not on the wire connecting my power rail to the resistor. Any ideas?

---

### Update:

Here is my corrected circuit per initial feedback. Please note this is still not working, but I think I'm getting close:

![enter image description here][2]

  [1]: https://i.stack.imgur.com/1dQW0.jpg
  [2]: https://i.stack.imgur.com/lxCrP.jpg

title: Simple LED circuit is not working

Answers: 2

body:
It looks like you've got confused between columns and rows.

You are correct that the power rails run the length of the breadboard -- these are seen as the top and bottom pairs of rows in the diagram below (ignore the middle row). However, the rest of the board is connected up as separate columns. Each column is independent of its adjacent columns.

![breadboard diagram][1]

This means your red wire going from the power rail to the resistor is connected correctly. However, the other end of your resistor is currently going nowhere. It needs to be in the same column as the anode of your LED.

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

body:
What connects the resistor to the LED?

![enter image description here][1]

Absolutely nothing.

It's hard to work out which holes the LED is plugged into, but I think your current circuit looks something like this:

![enter image description here][2]

You need to connect that resistor and LED together.

For your edit:

Now your circuit looks like this:

![enter image description here][3]

Behind the 5 pins in that column with the ground wire there is a big chunk of metal connecting them all together.  It's no different to if you'd taken the LED and twisted the pins together into one.  There's no way the power can get up one and down the other when they are connected together like that.  You need to separate them into different columns.

And this is how the (black) connections inside are laid out, and how your (red) electricity is flowing:

![enter image description here][4]

And here is how the circuit should look, using a program called Fritzing.  It's a pretty basic design tool, but great for showing wiring.

![enter image description here][5]

You can see how the green highlighting shows the columns that are connected.

  [1]: https://i.stack.imgur.com/E3mmD.png
  [2]: https://i.stack.imgur.com/moMz2.png
  [3]: https://i.stack.imgur.com/zM9rH.png
  [4]: https://i.stack.imgur.com/7Q11H.jpg
  [5]: https://i.stack.imgur.com/X23yu.png


body:
I am trying to send data from QSerialPort to Arduino Mega 2560. The proccess always takes some time to establish the connection.

***How do I know with QSerialPort is the connections is ready to send data?***

I don't know how much time do I have to wait for that and it happens every time when I run the application.

The configuration of my QSerialPort instance is:

    mSerialPort = new QSerialPort();
    mSerialPort->setPortName("COM3");
    mSerialPort->setBaudRate(QSerialPort::Baud9600);
    mSerialPort->setDataBits(QSerialPort::Data8);
    mSerialPort->setParity(QSerialPort::NoParity);
    mSerialPort->setStopBits(QSerialPort::OneStop);
    mSerialPort->setFlowControl(QSerialPort::NoFlowControl);
    mSerialPort->open(QIODevice::ReadWrite);

I check the device configuration of COM port:

![enter image description here][1]

I also changed and play the Arduino delay but nothing changed.

I am sending to Arduino little piece of data. Example:

    X100.10,Y10.23, H9999, ...others

And these data work when I am debugging the functions of my application. Everything is writting and work. So I am lost.

I hope all this information be usefull to give me an answer or at less some tips.

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

title: How do I know when the connections is ready between Arduino and QSerialPort

Answers: 1

body:
I am guessing that what you are seeing is not the port taking some time to open, but the Arduino resetting as soon as you open the serial port.  That means there is a short time while it's in the bootloader looking for an "I am here" signal from avrdude.  The timeout of that signal is configured in the bootloader, and is usually something like 1 second.

The simplest thing you can do is, as one of the first commands in your program, send an "I am ready to receive" signal to the computer (maybe just the word "OK" or something like that), which you then wait for before sending your data.


body:
I am sending data to Arduino using QtSerialPort. When I read the data the ouput has several not printer characters. I am using a QTexEdit (in left hand) to insert the data to send and other (in right hand) to insert  the data to read.

![enter image description here][1]

You can see the receive data has some no printer character.

# Workflow of sending and receiving data between QtSerialPort and Arduino

### Sending Data with QtSerialPort

    void MainWindow::sendData(){

        QString m_allData = m_sendEdit->toPlainText();
        int i = 0;
        int size = m_allData.size();

        QString line = "";
        int c = 0;
        while(i < size){
            line.append(m_allData[i]);
            if(c == 24){
                int sended = m_serialPort->write(line.toUtf8(), 24);
                m_serialPort->flush();
                line.clear();
                c = 0;
            }
            i++;
            c++;
        }
        if(c > 0){
            m_serialPort->write(line.toUtf8(), c);
        }
        m_serialPort->flush();
    }

I want to send the data with a buffer size of 24 bytes.

### Reading and Sending Data with Arduino

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

     void loop() {

      delay(1000);

       if (Serial.available() > 0){
         short i = 0;
         int size = Serial.available();
         String data = Serial.readString();
         Serial.print(data);
        }
     }

The Arduino code is simple.

### Receiving Data with QtSerialPort

    void MainWindow::readData(){
        int c = 0;
        char * dataBuffer;
        int size = m_serialPort->bytesAvailable();
        dataBuffer = new char[size];
        c = m_serialPort->read(dataBuffer, size);
        m_receiveEdit->setText(m_receiveEdit->toPlainText() + QString::fromUtf8(dataBuffer));
            delete dataBuffer;
    }

I am trying to read the same data that I send to Arduino. What kind of convertion do I have to do?

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

title: How do I print the reading serial data sending from Arduino

Answers: 1

body:
You have no warranty that Qt will receive the whole message in a single
chunk. It may receive "no se" as the first chunk, and then "q pasa" as
the second chunk. Since `dataBuffer` is dynamically allocated, it
initially contains garbage, and you are printing the part of this
garbage that you did not overwrite.

An easy fix would be to simply NULL-terminate the buffer:

<!-- language: lang-c++ -->

    dataBuffer = new char[size + 1];            // + 1 byte for '\0'
    c = m_serialPort->read(dataBuffer, size);
    dataBuffer[c] = '\0';                       // terminate the string


body:
I am using QtSerialPort to send and receive data from Arduino. I am sending **more than 64 bytes** (125, 220, more), I receive the data with Arduino, and trying to sending back the same data, but Arduino **sending only 64 bytes** in its response. Then I am thinking that the problem is with Arduino buffer. I am trying to clear the data but without result.

Here is my Arduino code:

    void loop() {
     if (Serial.available() > 0) {
      int i = 0;
      delay(500);
      int size = Serial.available();
      while (i < size)
       buffer[i++] = Serial.read();

      Serial.print(buffer);
      //delay(500);
      int j = 0;
      while (j < size)
       buffer[j++] = '\0';
      //while (Serial.available()) Serial.read(); I tried it
      //Serial.flush(); Also tried it, but nothing.
     }
    }

title: How do I receive more that 64 bytes with Arduino

Answers: 1

body:
Instead of blocking the loop for 500 ms, you should be actively
reading the data as it comes. Otherwise the internal buffer of the
`Serial` object will overflow after only 64 bytes are received.

Here is an example that copies the incoming bytes into a larger buffer
(256 bytes) and, upon receiving an end-of-line character, echoes
back the whole line.

<!-- language: lang-c++ -->

    void loop() {
        static char buffer[256];
        static size_t pos;              // position of next write

        while (Serial.available() && pos < sizeof buffer - 1) {

            // Read incoming byte.
            char c = Serial.read();
            buffer[pos++] = c;

            // Echo received message.
            if (c == '\n') {            // \n means "end of message"
                buffer[pos] = '\0';     // terminate the buffer
                Serial.print(buffer);   // send echo
                pos = 0;                // reset to start of buffer
            }
        }
    }


body:
I am trying to interface MPU6050 with arduino. Found a simple code online, but having a bit of trouble in interpreting it.

    // MPU-6050 Short Example Sketch
    // By Arduino User JohnChi
    // August 17, 2014
    // Public Domain
    #include<Wire.h>
    const int MPU=0x68;  // I2C address of the MPU-6050
    int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;
    void setup(){
    Wire.begin();
    Wire.beginTransmission(MPU);
    Wire.write(0x6B);  // PWR_MGMT_1 register
    Wire.write(0);     // set to zero (wakes up the MPU-6050)
    Wire.endTransmission(true);
    Serial.begin(9600);
    }
    void loop(){
    Wire.beginTransmission(MPU);
    Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
    Wire.endTransmission(false);
    Wire.requestFrom(MPU,14,true);  // request a total of 14 registers
    AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C     (ACCEL_XOUT_L)
    AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
    AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
    Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
    GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
    GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
    GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
    Serial.print("AcX = "); Serial.print(AcX);
    Serial.print(" | AcY = "); Serial.print(AcY);
    Serial.print(" | AcZ = "); Serial.print(AcZ);
    Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53);  //equation for   temperature in degrees C from datasheet
    Serial.print(" | GyX = "); Serial.print(GyX);
    Serial.print(" | GyY = "); Serial.print(GyY);
    Serial.print(" | GyZ = "); Serial.println(GyZ);
    delay(3330);
    }

Now there are a few things i want to ask regarding this code:
1. Here we have specified that the data from 3B register of the slave should be the first one and master will receive in total 14 bytes. In this case the 14 registers are continuous ([see datasheet here][1]) .Now how should i go about reading the values if i am interested in registers which are not continuous ,let us say alternative?

2.`AcX=Wire.read()<<8|Wire.read();`

This line is taking the first 8 bits and last 8 bits and forming a 16 bit number . But why do we need to shift the first 8-bits byte 8 places to left.Please explain how exactly this line works?

  [1]: https://www.olimex.com/Products/Modules/Sensors/MOD-MPU6050/resources/RM-MPU-60xxA_rev_4.pdf

title: Reading values from the register of a slave

Answers: 1

body:
For reading non-consecutive bytes, the “normal” way would be to do a
one-byte request and a one-byte read for each byte you want. However, if
the bytes you want are close enough (e.g. you want every other byte), it
would be faster to do a contiguous read and just ignore the bytes you do
not want. E.g.:

<!-- language-all: lang-c++ -->

    byte data1 = Wire.read();  // read first byte
    Wire.read();               // read and ignore second byte
    byte data3 = Wire.read();  // read third byte

For your question regarding the meaning of
`Wire.read()<<8|Wire.read();`:

1. `Wire.read()` return a 16-bit integer, where the 8 most significant
   bits are zero and the 8 least-significant bits contain the actual
   data. In binary, it's something like `00000000xxxxxxxx`, where `x`
   are the data bits.
2. `<<8` means “shift left by eight positions”, where the missing bits
   are replaced by zeros. Thus `Wire.read()<<8` is `xxxxxxxx00000000`
   in binary.
3. The second call to `Wire.read()` return another 16-bit integer in the
   form `00000000yyyyyyyy`.
4. The vertical bar `|` is the bitwise-or operator: each bit of the left
   operand is or-ed with the corresponding bit of the right operand to
   give one bit of the result: `x or 0` is `x`, `0 or y` is `y`.
5. Then, the whole expression gives `xxxxxxxxyyyyyyyy`, where `xxxxxxxx`
   comes from the first `Wire.read()` and `yyyyyyyy` from the second.

The problem here is that the “first” and “second” `Wire.read()` in the
sentence above refer to the position of the call in the line, not to the
actual order in which the calls are performed. Thus you may be lucky and
get the the correct byte order... or not. You should instead do a single
read per statement if you want to control the byte order. For MSB first:

    AcX = Wire.read() << 8;  // read most significant byte first
    AcX |= Wire.read();      // then least significant byte

And for LSB first:

    AcX = Wire.read();        // read least significant byte first
    AcX |= Wire.read() << 8;  // then most significant byte


body:
I was wondering whether anyone could help me... I am using an Arduino Uno and I am writing my code in the Arduino IDE. I am trying to implement the code so that the output voltage can be varied from 0 - 5 volts using 2 pushbuttons. I want to be able to increment the voltage by +0.5 volts from 0-5 volts every time I push Button A. Also I want to decrement the voltage by -0.5 volts from 5-0V every time I push Button B.

Example: (push Button A): output voltage 0.5: (push Button A): output voltage 1.0 etc.

So far when I upload my code the LED as my test for output just flickers between 2 - 4 volts. Can anyone tell me what I am doing wrong? I am not that good at coding so any help would be awesome.

Here is my code.

    int PWMPin = 6; // output pin supporting PWM
    int buttonApin = 8; // buttonA to pin 9 PWM
    int buttonBpin = 10; // buttonB to pin 10 PWM
    float value = 0; // read the value at 0
    float fadeValue = value;
    float counter = 0;

    void setup() {
      pinMode(buttonApin, INPUT);
      pinMode(buttonBpin, INPUT);
      pinMode(PWMPin, OUTPUT);
    }
    void loop() {
      int port = analogRead(0);
      port = map(port, 0, 10, 0, 255);
      analogWrite(6, port);
      if (digitalRead(buttonApin) == LOW, fadeValue) {
        if (counter >= 10) {
          counter = 10;
        }
        // fade from min to max in increments of 25.5 points: basically (0.5 volts)
        for(fadeValue = 0 ; fadeValue <= 255; fadeValue +=25.5) {
          counter = fadeValue;
          // sets the value (range from 0 to 255):
          analogWrite(PWMPin, fadeValue);
          delay(100);
        }
      }
      if (digitalRead(buttonBpin) == LOW, fadeValue) {
        if (counter <= 0) {
          counter = 0;
        }
        // fade from max to min in increments of 25.5 points: basically (0.5 volts)
        for(fadeValue = 255 ; fadeValue >= 0; fadeValue -=25.5) {
          counter = fadeValue;
          // sets the value (range from 0 to 255):
          analogWrite(PWMPin, fadeValue);
          delay(100);
        }
      }
    }

title: Arduino Uno coding problem voltage varying

Answers: 1

body:
There's a number of very basic things wrong with your code - things that aren't doing what you think, or you just telling it completely the wrong things.

Start by formatting your code properly (INDENTS!) and match up all your brackets.  You'll soon see what I see as far as what is wrong.

I'll give you some clues:

----

    {
    if (digitalRead(buttonApin) == LOW, counter)

Where to I start with that one...?

----
    for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=25.5)
      counter = fadeValue;
      digitalWrite(PWMPin, fadeValue);
C is not Python!

----

    digitalWrite(PWMPin, fadeValue);
Writing an analog value to a digital pin?!

----

    Serial.println(PWMPin);
Printing the pin number - now what is the point of that?

----

    ... fadeValue += 25.5 ...

Adding a float to an integer - bad practice (and ultimately pointless) - pick one, float or integer, and stick to it.

----

And then there is the whole logic of your program. I can't work out what it's supposed to be achieving.  It looks like you've tried to get it to do all sorts of parts of different things and not got it to do anything at all.  Strip it right out and get it to do ONE thing - provide a specific, STATIC, voltage.  Then add in some way of changing that voltage afterwards.


body:
I want to buy this kit: http://www.banggood.com/UNO-Basic-Starter-Learning-Kit-Upgrade-Version-For-Arduino-p-970714.html

However, as shipping stuff from China takes like 3 months to arrive, i need to be certain i won't have much else to buy.

How far can i go just with this kit, and what would you recommend me buying together with it?

Thanks in advance.

title: How far can i go just with this starter kit?

Answers: 0


body:
Windows 7 here. I just bought an [Arduino Due](http://www.arduino.cc/en/Main/ArduinoBoardDue) and downloaded the Arduino IDE. I wrote a simple "blink LED" program (see below) and am trying to flash it to the Due.

When I connected the Due to my laptop (via micro USB cable), I got a warning on my laptop that it could not find the correct device driver. So I followed the instructions discussed on [this excellent video tutorial](https://www.youtube.com/watch?v=fCxzA9_kg6s) and went into `Control Panel >> System >> Device Manager >> Arduino` and pointed it to load the appropriate device driver from `C:\Program Files (x86)\Arduino\drivers`. This got rid of the warning. Hooray!

I then Verified & Compiled my program:

    int led = 13;

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

    void loop() {
        digitalWrite(led, HIGH);
        delay(5000);
        digitalWrite(led, LOW);
        delay(5000);
    }

Great success! Now it was time for me to upload the program to my Due. The first time I tried to upload it, I got the following error:

    Arduino: 1.6.4 (Windows 7), Board: "Arduino Uno"
    Sketch uses 1,068 bytes (3%) of program storage space. Maximum is 32,256 bytes.
    Global variables use 11 bytes (0%) of dynamic memory, leaving 2,037 bytes for local variables. Maximum is 2,048 bytes.
    avrdude: ser_open(): can't open device "\\.\COM1": The system cannot find the file specified.

    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

        This report would have more information with
        "Show verbose output during compilation"
        enabled in File > Preferences.

So then in the IDE I went to `Tools >> Port` and changed the selection from `Serial` to `COM3` (again, sort of explained in that video tutorial). I tried to upload again:

    Arduino: 1.6.4 (Windows 7), Board: "Arduino Uno"
    Sketch uses 1,068 bytes (3%) of program storage space. Maximum is 32,256 bytes.
    Global variables use 11 bytes (0%) of dynamic memory, leaving 2,037 bytes for local variables. Maximum is 2,048 bytes.
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x09
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x09
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x09
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x09
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x09
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x09
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x09
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x09
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x09
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x09

    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

        This report would have more information with
        "Show verbose output during compilation"
        enabled in File > Preferences.

I thought it was interesting that the IDE thinks this is an Arduino Uno. So then I went to `Tools >> Board` and changed the selection from `Uno` to `Duemilanove`, hoping that Due and Duemilanove are compatible for the programmer/flasher tool. This time the error was the same as last, except the first line reads:

    Arduino: 1.6.4 (Windows 7), Board: "Arduino Duemilanove or Diecimila, ATmega328"

So at least the IDE is switching board correctly. :-) I should note that my `Tools >> Board` menu **does not** have an "Arduino Due" option. And when I go to `Tools >> Board >> Board Manager`, searching for Due does not turn up anything either.

I also tried running the upload with verbose output, but that really didn't tell me anything more. I'm happy to post the exact verbose output but figured I could omit it here for brevity. I also *did* peruse the [troubleshooting link](http://www.arduino.cc/en/Guide/Troubleshooting#upload) that the error output recommends, but it looks like I've already exhausted all of those recommendations as well.

I'm stuck and frustrated, any suggestions?

What do I need to do to get the IDE programming my Due?

title: Problems uploading sketch to Arduino Due

Answers: 2

body:
> ... hoping that Due and Duemilanove are compatible for the programmer/flasher tool.

Not even close. You will need to go into the Boards Manager and download and install the SAM support files, select the Due from the list, and *then* upload the sketch.

body:
Yes, I just had this problem myself..
Unless you use the Boards Manager Menu and install the Arduino SAM Boards (32Bits ARM cortex M3) board info you will not be able to upload your sketch.
After installing in the Boards Manager you will see the Arduio Due programming port and Arduino Native port as an extra options at the bottom or the TOOLS>BOARD menu.
That should fix the problem.(Check which you are connected to and which COM port)
If you still have trouble, disconnect and reconnect the DUE and restart the IDE and if required restart you computer.

This seems to be a common problem when people switch from the Uno or MEGA to the Due. I'm surprised this is not installed as standard in the IDE. I am using 1.6.5r2.

Thanks also to Ignacio Vazquez-Abrams.


body:
So I am programming an LED Music Visualizer that uses a combination of Processing and Arduino. I have it all working as I want to but there is a small problem. If I were to stop the music, then the Arduino will keep displaying the visualization for a few seconds. I believe that this issue would be caused by it "catching up" on new serial data from Processing like a queue. So my question is: When arduino uses the Serial.read() function, is it using the most recent value or is it using the next value received after the last one that it used, like a queue of values.

**Example**: Processing sends the values 1,2,3,4,5,6,7,8,9 over serial in 10 millisecond intervals. Arduino only performs Serial.read at 20 millisecond intervals. Would the arduino read the values 1,3,5,7,9 in or would it read the values 1-9 but in twice the time?

Sorry for the confusing question, hopefully somebody could shed some light. At the core, it is a question on how serial works, you can ignore the part about the music visualizer.

title: Arduino Serial Queue

Answers: 2

body:
It sounds like you figured most of your question out already.

 (Someone correct me here if I'm wrong). The Atmega 328p uC, I believe, has an 8 byte hardware buffer for RX serial data. In software, the Arduino core code defines a maximum ring buffer of 64 bytes that acts as a FIFO queue.

So, what does his mean? Let's just focus on the hardware buffer since it's fairly easy. Say you send your data 1,2,...,10 at 10ms intervals, and you read your data at 100ms intervals (for illustration purposes). The problem is that you send 10 bytes of data but only have room for 8 bytes. So, your first two values (1,2) are pushed out of the buffer and lost. This idea also illustrates a FIFO queue, first in first out.

The same idea can be extended to a ring buffer.

Anyway, like you said, this could explain your problem. If you have 64 bytes, which will obviously be full since your inevitably losing data (20ms read with a 10ms write), you'll be seeing the effects for 64 * 20ms = 1.28s. There's probably some processing delay too which will extend this delay, but it's more than likely minimal if it's efficient code.

body:
> Arduino only performs Serial.read at 20 millisecond intervals.

It sounds like you're using `delay` to pace the reads.  But why?  You'll start to lose data after reading just 3 or 4 characters (60ms to 80ms).  Serial at 9600 can send 1 character per millisecond, 20 times faster than you are reading them.

If you edit your post to include your code, we might be able to make a suggestion to eliminate that delay.


body:
I am building a 2-Axis gantry system to dispense some thermal paste on boards. I was given two stepper motors in order to do so along with a gantry already built that will arrive in two weeks. So basically I just need to figure out how to drive them on the software side. However the boss demands testable code to be finished by EOB tomorrow, despite the hardware not being here yet. So I drafted some quick code that should drive a stepper motor, it's an easy open loop system, but I'm struggling. The operator will home the gantry after each cycle so it's just a matter of getting the motors moving.

My method was as follows:

    #include <Stepper.h>
    *declaring the stepper and all that goes here*
    void loop(){ etc.
       basic logic flow stuff
       stepper.step(20); // to move forward twenty steps
       stepper.step(-20) // to move back twenty steps

However my boss says this is incorrect as I need to be giving the steppers both *step* and *direction*.

 After some tenuous google searching he recommended I use the AccelStepper library to fix this problem. After looking through this library I'm unsure how this will give me anything I need (distances are so small acceleration is useless) and how I am not giving it both step and direction in my original example code, I give it steps (20) and a direction with my negative/positive coefficient.

Am I correct in my thinking? Is there a better solution neither of us have found? I'd love to understand not just that I'm wrong, but why I am.

title: Help understanding how to drive Step motors with Arduino

Answers: 1

body:
I think there is some mis-communication between you and your boss. I do not think your boss is stupid, but I do think he's talking on a different level as you do. You're using arduino which covers up a lot of hardware-interfacing, especially with steppers.
I suggest you check out this video: https://www.youtube.com/watch?v=bngx2dKl5jU
(I haven't watched it, but It will help you get more into the ideas of your boss)

Now you understand your boss's view, you can try to show him your view. When talking about steppers/arduino and how you can put in negative steps, he might think you're talking trash, as steppers require different pairs of coils to be active depending on the direction. (which is all handled by arduino)
The best way is to provide him a visual guidance, so that he can see the relation with his (hardware-view) on the issue and your software/arduino solution.

You could make something like the image below.
I'm not sure if this is what you're trying to tell him.
I guess you should mention/add that the software on the arduino takes integer values, with negative values being clockwise or such. **And that the arduino will convert this to the right coil pairs or direction and step.**

P.S:with *direct driving*, I think he meant toggling the right pins at the right moments so that the stepper will rotate, basically what the stepper library does for you. Maybe he wants you to implement something like the stepper library (is it an internship? so that you can learn?) I suggest you check some tutorials on how stepper motors work, and how you can drive them 'directly' withouth the use of libraries.

![Example][1]

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


body:
I need to transfer files from my local machine to my Arduino Yun.

I have tried:

    scp /Users/SSCirrus/Documents/index.html root@arduino.local:/root
    scp ~/Users/SSCirrus/Documents/index.html root@arduino.local:/root
    # No such file or directory (referring to my desktop)

I have confirmed that the filepath is accurate. What's wrong here?

title: How to copy files from local computer to Yun with scp?

Answers: 1

body:
Try `~/Documents/index.html`

The `~` represents the current user's home directory, so `~/Documents` is the Documents folder for the current user.  It means you don't have to make sure you have spelled the user's home directory exactly right.

Other options are:

* `$HOME/Documents/index.html`
* `Documents/index.html` (if you are in your home directory)
* `cd ~/Documents` then just use `index.html`

... the list goes on ...


body:
For a school project we're working on a wearable device to track people's movement and heart rate. We use an Arduino Pro Mini with a heartbeat sensor and an accelerometer. The wearable device uses Bluetooth to send data, but only once or twice a day to save battery.

The problem we currently face is having the Arduino keep track of the accelerometer data while also reading the heartbeat sensor on a select interval. See the pseudo-code underneath. In what way (preferably without implementing too many libraries) could we merge these two loops so the accelerometer is read non-stop while keeping an interval (of about 30 minutes) between the heart beat readings? Any input would be greatly appreciated and if needed I can provide additional information.

    void loop() {
    // Heartbeat sensor loop
      while (array is not full) {
        delay(30 minutes);
        heartbeatArray[index++] = readHeartbeat();
      }
      sendData_Bluetooth(heartbeatArray);
      emptyArray();
    // End of heartbeat sensor loop

    // Accelerometer loop
      while (true)
        if (readAccelerometerData > limit)
          sendAlert();
    // End of accelerometer loop
    }

title: Running multiple tasks at once

Answers: 4

body:
millis() is your great friend here.

millis() is function that returns the value of a 32 bit counter that is incremented once per millisecond. By adding the current value returned by millis() to a value representing the number of milliseconds that you want to 'delay' for you get a value that can be compared with the ongoing value returned by millis() to see if the time period has elapsed.

You can have as many variables as you wish which hold future timeout values for millis(0 - you perform the related action when millis() returns >= the saved value and reinitialise the value to some new future time.

Variables used to hold values from millis() **MUST** be type unsigned long.
The millis() timer rolls over every 49.7 days.
( = 2^32/1000 ms/s / 3600 s/hr / 24 h/day)

 - If your system may run for longer than that without being reset or powered down then handling millis()'s timer rollover must be known about.

   It's MUCH easier than many people realise but best not dealt with here EXCEPT to know that if you add a constant to millis() and the value exceeds 2^32 and is truncated the comparisons with and subtractions wrt millis() still work correctly if the variable is type unsigned long. ("Why" is for elsewhere)

micros() is like unto millis() but returns the time since reset in microseconds. Depending on the processor used micros() may have a granularity of 4 uS rather than one uS. ie it steps by 4 counts every 4 uS rather than 1 count per uS.
micros() rolls over every 1.19 hours
( = 2^32 / 10^6/3600s/h)

________________

// **Example - not tested:**

    unsigned long DoitNow;

    void setup(){
      DoitNow = millis() + 1800000; // Add half an hour of milliseconds
     }
    void loop(){
       if(millis() > DoitNow)
       { Do heartbeat stuff;
          DoitNow = millis() + 1800000; // Add another half hour of ms
       }
     Do accelerometer stuff;
    }

body:
What you want to do is rather easy task, you just need to forget about `delay()` function. When writing some more complex programs using it is generally a bad idea, as it blocks code execution, so you won't get any sensor readings, communication, anything. Instead try something like this:

    unsigned long delay1 = 100;
    unsigned long delay2 = 1800000; //30 minutes in miliseconds
    unsigned long t1, t2;

    void setup() {
      t1 = t2 = millis();
    }

    void loop() {
      if(millis() - t1 > delay1) { //this will be executed every delay1 ms
        // do one part of code
        t1 = millis();
      }

      if(millis() - t2 > delay2) { //this will be executed every delay2 ms
        // do another part of code
        t2 = millis();
      }

      // here insert the code that should be executed as frequently as possible
      // (every loop passage)
    }

There is also a nice Arduino library called [TaskScheduler][1], that basically does the same thing: periodically executes different functions with different time intervals.

  [1]: http://playground.arduino.cc/Code/TaskScheduler

body:
To keep the 10Hz accelerometer sample rate consistent, you'll need an 10Hz interrupt routine to do the sampling, and probably queue them somewhere, as they will accumulate while you're off measuring the heart rate.

Your main loop can collect any accelerometer samples out of the queue periodically, and at appropriate intervals, read the heart beat. This organization will keep the accelerometer sample rate stead whether your main loop has anything else to do or not.

Make the queue more than long enough to hold all the samples that could collect during a heartbeat measurement, which you should probably make one at a time, even though you might do it in rapid succession, so the main loop gets to drain the accelerometer queue as often as possible.

Otherwise you'll need a queue as large as (10 Hz * 10 sec * maxPossibleConsecutiveHeartBeatMeasurements * factorOfSafety * sizeof(oneSample) bytes; and you don't have a whole lot of memory to play with in an Atmega 328.

Where will you be storing the measurements between Bluetooth connects? If it's an SD card, you'll need some space for its write-buffer, and the main loop will have to manage the card writing.

body:
See https://electronics.stackexchange.com/a/67091/10371 (Since this is another stack exchange site, I won't copy the info)

The short answer is to use timers that trigger interrupts.  Examples are shown in the link.