Id
stringlengths
1
5
Tags
stringlengths
3
75
Title
stringlengths
15
150
CreationDate
stringlengths
23
23
Body
stringlengths
51
27.6k
Answer
stringlengths
42
31k
10344
|serial|programming|
Arduino Java SerialEvent not being called (Rasberry PI) XPOST from stack overflow
2015-04-26T14:26:47.917
<p>I am following a simple example <a href="http://openenergymonitor.org/emon/javaexamples" rel="nofollow noreferrer">found here (example one)</a>, to have an Arduino connected to a Raspberry Pi and read some data from the Arduino on the Pi in Java.</p> <p>The issue is that the SerialEvent method is never called, which implies that no data is coming in. However, when I open the Serial Monitor I can see that data is being read correctly.</p> <p>The correct serial port is being used as well.</p> <p>Here is the Java code.</p> <pre><code>//This class: // - Starts up the communication with the Arduino. // - Reads the data coming in from the Arduino and // converts that data in to a useful form. // - Closes communication with the Arduino. //Code builds upon this great example: //http://www.csc.kth.se/utbildning/kth/kurser/DH2400/interak06/SerialWork.java //The addition being the conversion from incoming characters to numbers. //Load Libraries import java.io.*; import java.util.TooManyListenersException; //Load RXTX Library import gnu.io.*; class ArduinoComm implements SerialPortEventListener { //Used to in the process of converting the read in characters- //-first in to a string and then into a number. String rawStr=""; //Declare serial port variable SerialPort mySerialPort; //Declare input steam InputStream in; boolean stop=false; public void start(String portName,int baudRate) { stop=false; try { //Finds and opens the port CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(portName); mySerialPort = (SerialPort)portId.open("my_java_serial" + portName, 2000); System.out.println("Serial port found and opened"); //configure the port try { mySerialPort.setSerialPortParams(baudRate, mySerialPort.DATABITS_8, mySerialPort.STOPBITS_1, mySerialPort.PARITY_NONE); System.out.println("Serial port params set: "+baudRate); } catch (UnsupportedCommOperationException e) { System.out.println("Probably an unsupported Speed"); } //establish stream for reading from the port try { in = mySerialPort.getInputStream(); } catch (IOException e) { System.out.println("couldn't get streams"); } // we could read from "in" in a separate thread, but the API gives us events try { mySerialPort.addEventListener(this); mySerialPort.notifyOnDataAvailable(true); System.out.println("Event listener added"); } catch (TooManyListenersException e) { System.out.println("couldn't add listener"); } } catch (Exception e) { System.out.println("Port in Use: "+e); } } //Used to close the serial port public void closeSerialPort() { try { in.close(); stop=true; mySerialPort.close(); System.out.println("Serial port closed"); } catch (Exception e) { System.out.println(e); } } //Reads the incoming data packets from Arduino. public void serialEvent(SerialPortEvent event) { //Reads in data while data is available while (event.getEventType()== SerialPortEvent.DATA_AVAILABLE &amp;&amp; stop==false) { try { //------------------------------------------------------------------- //Read in the available character char ch = (char)in.read(); //If the read character is a letter this means that we have found an identifier. if (Character.isLetter(ch)==true &amp;&amp; rawStr!="") { //Convert the string containing all the characters since the last identifier into an integer int value = Integer.parseInt(rawStr); if (ch=='A') { System.out.println("Value A is: "+value); } if (ch=='B') { System.out.println("Value B is: "+value); } //Reset rawStr ready for the next reading rawStr = (""); } else { //Add incoming characters to a string. //Only add characters to the string if they are digits. //When the arduino starts up the first characters it sends through are S-t-a-r-t- //and so to avoid adding these characters we only add characters if they are digits. if (Character.isDigit(ch)) { rawStr = ( rawStr + Character.toString(ch)); } else { System.out.print(ch); } } } catch (IOException e) { } } } } </code></pre> <p>And here is the Arduino Sketch</p> <pre><code>//Arduino code for Part 01 //First we will define the values to be sent //Note: The java code to go with this example reads- //-in integers so values will have to be sent as integers int valueA = 21; int valueB = 534; void setup() { Serial.begin(115200); Serial.println("Start"); } void loop() { //We send the value coupled with an identifier character //that both marks the end of the value and what the value is. Serial.print(valueA); Serial.print("A"); Serial.print(valueB); Serial.print("B"); //A delay to slow the program down to human pace. delay(500); } </code></pre> <p>I have read that changing <code>Serial.print()</code> to <code>Serial.write()</code> is the new way to do this, but changing this had no result. </p>
<p>So the reason for no events being triggered was due to the program exiting and ending before it had the chance to.</p> <p>To solve this i added a thread with a loop inside it inside the main thread.</p> <pre><code>public static void main(String[] args) throws Exception { ArduinoComm = new ArduinoComm (); main.start("/dev/ttyUSB0",115200); Thread t=new Thread() { public void run() { try { //Messy implementation but it works for this demo purpose while(true){ //optional sleep thread.Sleep(500); } } catch (InterruptedException ie) {} } }; t.start(); System.out.println("Started"); } </code></pre> <p>Bit of an oversight on my part. </p>
10355
|gsm|gps|
Arduino UNO + Arduino GSM Shield + Sparkfun Venus GPS
2015-04-27T01:56:40.113
<p>I am using an Arduino UNO that is connected to an Arduino GSM shield (<a href="http://www.arduino.cc/en/Main/ArduinoGSMShield" rel="nofollow">http://www.arduino.cc/en/Main/ArduinoGSMShield</a>).</p> <p>Now, I want to connect the SparkFun Venus GPS module to this combination. (*unfortunately due to my rep I can only post two links) </p> <p>The Venus GPS works fine with the Arduino UNO by itself, but I am having some trouble getting the GPS module to communicate with the Arduino when the GSM shield is stacked on top. </p> <p>The GPS powers on and begins blinking (which means it has a lock), but the serial monitor is not showing any information.</p> <p>Coming from the programming side of things, I really don't understand much about electronics, so please pardon me if I am missing something basic here. </p> <p>Based on what I've managed to figure out so far, I think it has something to do with the shield requiring 5V operating voltage and the Venus operating at 3.3V. </p> <p>I think that when the GSM shield is plugged in, its expecting a 5V input, but the Venus GPS is only capable of sending a 3.3V signal. Furthermore, any other 5V sensors that I am currently using don't have any problems communicating with the UNO through the GSM shield.</p> <p>So, I actually have two questions:</p> <ol> <li>Is this assumption correct or could something else be the cause of my issue?</li> <li>If this is correct, could I use something like this logic level converter (<a href="https://solarbotics.com/product/50550/" rel="nofollow">https://solarbotics.com/product/50550/</a>) to step up the Venus GPS input signal? </li> </ol> <p>Thank you in advance for any help and guidance you are able to provide.</p>
<p>I received my logic level converter today and wired it in between the Venus GPS and the Arduino GSM shield. </p> <p>The issue seems to be resolved and I'm able to properly receive information from the TX on the Venus GPS. It would seem that my assumption was correct and I needed to "step-up" the 3.3V TX signal from the Venus GPS in order to use it with the GSM shield. </p>
10357
|arduino-uno|c++|led|arduino-ide|adafruit|
Arduino with WS2812 using Adafruit NeoPixel library fade in/out different patterns
2015-04-27T04:11:50.250
<p>Hey all I have been trying to figure out a way to random set patterns for my fade in/ out code below:</p> <pre><code>int PIN = 3; int totalLEDs = 11; int ledFadeTime = 5; Adafruit_NeoPixel strip = Adafruit_NeoPixel(totalLEDs, PIN, NEO_GRB + NEO_KHZ800); void setup() { strip.begin(); strip.show(); // Initialize all pixels to 'off' } void loop() { rgbFadeInAndOut(0, 0, 255, ledFadeTime); // Blue } void rgbFadeInAndOut(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) { for(uint8_t b = 0; b &lt;255; b++) { for(uint8_t i=0; i &lt; strip.numPixels(); i++) { strip.setPixelColor(i, red * b/255, green * b/255, blue * b/255); } strip.show(); delay(wait); }; for(uint8_t b=255; b &gt; 0; b--) { for(uint8_t i = 0; i &lt; strip.numPixels(); i++) { strip.setPixelColor(i, red * b/255, green * b/255, blue * b/255); } strip.show(); delay(wait); }; }; </code></pre> <p>The code above works great. Fades the blue in and out infinity times. However, I am wanting random LEDs to be off or have a lighter/darker shade of the color I choose (in the above it's blue).</p> <p>Example:</p> <pre><code>[off][blue][blue][off][off][dark blue][blue][off][dark blue][dark blue][off] [blue][blue][blue][dark blue][off][blue][dark blue][blue][dark blue][off][off] etc etc... </code></pre> <p>Would anyone happen to have code already like this?</p> <p>Any help would be great! Thanks!</p>
<p>To make randomly-changing colours for the whole strip, change:</p> <pre><code>void loop() { rgbFadeInAndOut(0, 0, 255, ledFadeTime); // Blue } </code></pre> <p>to:</p> <pre><code>void loop() { rgbFadeInAndOut(random (256), random (256), random (256), ledFadeTime); // random colour } </code></pre> <hr> <p>If you want to make individual pixels different colours you could set up an array of colours, randomly initialize it, and use that. Like this:</p> <pre><code>#include &lt;Adafruit_NeoPixel.h&gt; int PIN = 3; int totalLEDs = 11; int ledFadeTime = 5; Adafruit_NeoPixel strip = Adafruit_NeoPixel(totalLEDs, PIN, NEO_GRB + NEO_KHZ800); void setup() { strip.begin(); strip.show(); // Initialize all pixels to 'off' } void loop() { rgbFadeInAndOut(ledFadeTime); } void rgbFadeInAndOut(uint8_t wait) { uint8_t red [totalLEDs]; uint8_t green [totalLEDs]; uint8_t blue [totalLEDs]; // randomly set each colour for (int i = 0; i &lt; totalLEDs; i++) { red [i] = random(256); green [i] = random(256); blue [i] = random(256); } for(uint8_t b = 0; b &lt;255; b++) { for(uint8_t i=0; i &lt; strip.numPixels(); i++) { strip.setPixelColor(i, red [i] * b/255, green [i] * b/255, blue [i] * b/255); } strip.show(); delay(wait); } for(uint8_t b=255; b &gt; 0; b--) { for(uint8_t i = 0; i &lt; strip.numPixels(); i++) { strip.setPixelColor(i, red [i] * b/255, green [i] * b/255, blue [i] * b/255); } strip.show(); delay(wait); } } </code></pre>
10362
|programming|
What is the best way to define an I/O pin?
2015-04-27T06:11:54.427
<p>I read definitions like</p> <pre><code>const int ledPin = 9; </code></pre> <p>and also</p> <pre><code>#define ledPin 9 </code></pre> <p>I know that a definition like</p> <pre><code>int ledPin = 9; </code></pre> <p>is a bad practice if you're not going to change it (which you usually won't), though I've see this several times in Arduino programs. Which one of the other two is preferred?</p>
<p>Probably the best way would be<br> <code>const uint8_t LED_PIN = 9; // may require to #include &lt;stdint.h&gt;</code><br> or<br> <code>const byte LED_PIN = 9; // with no include necessary</code><br> <code>const unsigned char LED_PIN = 9; // similarly</code><br> The name is in caps as per general practice in C++ (and others) to name constants. This should not use any RAM in itself, and use about 1 byte of program memory per use.<br> However, there <em>might</em> be problems when the number is higher than 127 and is sign-extended while getting promoted to larger signed integers (not entirely sure on this), although that is unlikely to happen with pin numbers.</p>
10368
|current|
ATMega I/O maximum current
2015-04-27T12:37:05.633
<p>According to the ATmega328P datasheet, the total current from <strong>all I/O pins</strong> must not exceed 200mA. </p> <p>Let's say that an Output pin sources 30mA and an Input pin sinks 10mA. The total current should be 30+10=40mA or 30-10=20mA? </p>
<p>Neither. First, inputs don't draw current. Whether you're sourcing current or draining it, it will always be an output pin.</p> <p>The 200 mA rule is probably determined by the bonding wires for the Vcc and ground pins on the die. That means that all outputs which are sourcing current shouldn't source more than 200 mA combined, as this current will have to enter the device through the Vcc pin.<br> Likewise all outputs sinking current shouldn't sink more than 200 mA combined, as this current will drain through the ground pin.</p>
10369
|current|
calculating the input current
2015-04-27T12:53:25.783
<p>I have been a bit confused about calculating the input current, so I'd be much obliged if someone could help.</p> <p>Let's say that we have a potentiometer connected with an analog input as shown below. In a middle position the resistance of the potentiometer is spitted to R1 and R2.</p> <p>How can I calculate the current in A0? How much will be the current value if (R1=0, R2=Rmax), (R1=Rmax, R2=0), (R1 and R2 !=0,Rmax)?</p> <pre><code> 5V -------- | R1 | A0 -------- | R2 | GND </code></pre>
<p>The input current of the ADC is low enough not to change the potentiometer's characteristic (which won't be perfectly straight, anyway).</p> <p>The only requirement is that the impedance of the potentiometer (according to Thévénin equal to R1 parallel to R2) shouldn't be greater than 10 k&Omega;. That's because otherwise it takes too long for the ADC's capacitor to get charged.</p>
10372
|i2c|mpu6050|
Do I need Kalman Filter after I read DMP data on MPU6050?
2015-04-27T13:26:49.343
<p>In my project I need to use as noiseless as possible data from a MPU6050, I do have some nice DMP data, what will happen if I apply Kalman filter above it? Will I get more noiseless data? Or will it become unreliable anymore? Are there any benefits to do that ?</p>
<p>The DMP data from the MPU6050 is already filtered, and while I have not expirimented with the DMP data much myself I believe it is pretty clean. If there is a calibration process you can do to improve it, that is probably worth expirimenting with, but you should not filter the values a second time.</p> <p>You should figure out what your application's noise tolerance actually is before worrying about different filters. There are potential benefits to your own filter, I think knowing exactly how it performs in edge cases and being able to calibrating it to your specific problem could be beneficial; However, it could also end up being worse than the DMP. Don't forget that filter calculations can generally take a few milliseconds for an arduino to run that you don't have to worry about with the DMP.</p> <p>If you do work on your own filter, you will need to turn off the DMP and filter the raw values. Look into complementary, mahoney, and madgwick filters as well as kalman, which is quite computationally expensive. Using an existing library or an implementation from an open source quadcopter project is probably most efficient. The math associated with kalman filters and 3d rotations gets very complicated very quickly.</p>
10385
|arduino-uno|i2c|lcd|osx|
LCD Display hangs the computer
2015-04-27T18:44:48.247
<p>I'm trying to connect 16x2 LCD screen to clone Arduino UNO via PF8574T backpack. 4 cables are connected to +5V, GND, SDA and SDL pins.</p> <p><strike>When I tried <a href="http://playground.arduino.cc/Main/I2cScanner?action=sourceblock&amp;num=1" rel="nofollow">this</a> I2C scanner code from arduino.cc. It returned strange characters in serial monitor at first couple of tries. And now, when I try computer hangs.</strike></p> <p>When I use A4 A5 pins on the Arduino instead of SDA and SDL, i2c reported the device is on 0x27. It is ok. But if i keep LCD connected to Arduino, my iMac shutdowns after for a while. In error log i see there was a problem regarding USB serial device. I assume it as a power problem. </p> <p>I'm on OS X Yosemite. Why this can be happening and how can I fix? </p> <p>Note: Computer is hanging as soon as the Arduino usb cable connected.</p>
<p>Sometimes my system hangs in the way you describe ("hanging as soon as the Arduino usb cable connected") if I mistakenly connect the +ve and -ve supply lines to an i2c device the wrong way round. </p>
10387
|arduino-uno|serial|led|
Serial LED control
2015-04-27T19:21:49.227
<p>Hell0!</p> <p>I run in small problem. I am try to control LED's by serial port.So I am expect to send "1" and two LED's will start to blink or send "0" and only one LED is constantly lighted up. At first I thought that do-wile will work, Arduino will run do loop while value sent by serial port is "1" or "0". However at first I sent "0" and one LED are lighted, after I send "1" and two LED's are blinking. But when I send "0" again, LED's keeps blinking. What should I change in my code?</p> <pre><code>const int ledPin2=2; const int ledPin3=3; const int ledPin4=4; void setup() { pinMode(ledPin2, OUTPUT); pinMode(ledPin3, OUTPUT); pinMode(ledPin4, OUTPUT); Serial.begin(9600); } void loop() { while (Serial.available()==0); int serialVal = Serial.read()-'0'; do { digitalWrite(ledPin3, LOW); digitalWrite(ledPin4,HIGH); } while(serialVal==0); do { digitalWrite(ledPin4,LOW); digitalWrite(ledPin2, HIGH); digitalWrite(ledPin3, LOW); delay(100); digitalWrite(ledPin3, HIGH); digitalWrite(ledPin2, LOW); delay(100); }while (serialVal==1); }; </code></pre>
<p>I don't think you understand how your code is being executed. I would recommend trying the following.</p> <pre><code>const int ledPin2=2; const int ledPin3=3; const int ledPin4=4; int serialVal; void setup() { pinMode(ledPin2, OUTPUT); pinMode(ledPin3, OUTPUT); pinMode(ledPin4, OUTPUT); Serial.begin(9600); } void loop() { // If data is available, then read it! if (serial.available() &gt; 0) { serialVal = serial.read()-'0'; } // If serial val is 1, turn on LEd4, turn off Led3 if (serialVal == '1') { digitalWrite(ledPin3, LOW); digitalWrite(ledPin4,HIGH); } // If serial val is 0, // turn on LED2. Turn off Led3 // delay for 100ms // turn of LED2, turn on LED3 // delay for 100 ms if (serialVal == '0') { digitalWrite(ledPin4,LOW); digitalWrite(ledPin2, HIGH); digitalWrite(ledPin3, LOW); delay(100); digitalWrite(ledPin3, HIGH); digitalWrite(ledPin2, LOW); delay(100); } } </code></pre> <p>The reason why your code doesn't work, is once you are within a do while loop, you will not be allowed to exit until the condition is met. If you are not scanning for more serial values within that do while, you will get stuck there forever.</p> <p>Another reason why you might be confused, is how digitalWirte operates. There is no need to loop over a digitalWrite, as the pin will stay HIGH, or LOW until you change its state. Once you digitalWrite(HIGH) that pin will stay high until it is told to go LOW.</p>
10389
|arduino-uno|c++|servo|timers|
Why does timer1 not generate correct period on CTC mode with a resolution of 5us?
2015-04-27T20:16:14.703
<p>I have defined my code to generate an interrupt over each 5&mu;s on CTC mode using timer1 but the output shows a time of ~15&mu;s.</p> <p>Following the equation to set the counting number to achieve the desired time </p> <pre><code>(# timer counts + 1) = (target time) / (timer resolution) </code></pre> <p>I've got OCR1A = 79 for a desired time of 5&mu;s using no prescaler and a source clock of 16MHz on Arduino Uno.</p> <p>My code is as follows:</p> <pre><code>// avr-libc library includes #include &lt;avr/io.h&gt; #include &lt;avr/interrupt.h&gt; #define LEDPIN 9 void setup() { pinMode(LEDPIN, OUTPUT); digitalWrite(LEDPIN, HIGH); // initialize Timer1 cli(); // disable global interrupts TCCR1A = 0; // set entire TCCR1A register to 0 TCCR1B = 0; // same for TCCR1B // set compare match register to desired timer count: OCR1A = 79; // turn on CTC mode: TCCR1B |= (1 &lt;&lt; WGM12); // Set CS10 bit for no prescaler: TCCR1B |= _BV(CS10); // enable timer compare interrupt: TIMSK1 |= (1 &lt;&lt; OCIE1A); sei(); // enable global interrupts } void loop () {} ISR(TIMER1_COMPA_vect) { digitalWrite(LEDPIN, !digitalRead(LEDPIN)); } </code></pre> <p>This is the output from my logic analyzer:</p> <p><img src="https://i.stack.imgur.com/ft4Ti.png" alt="Output From Logic Analyzer"></p> <p>Is it a limitation of the Arduino or am I missing something?</p> <p>My idea is to generate a PWM manually to control a servo motor using timer1 and precisely increase the period by 10&mu;s during "on" time and get the desired angle. </p> <p>After some experiments, I have discovered that my motor (<a href="http://www.servodatabase.com/servo/towerpro/mg996r" rel="nofollow noreferrer">MG996R</a>) has a range from 0.6ms to 2.1ms during "on" time to move from 0 to 180 degrees.</p> <p>I have tried the Arduino's Servo library but it goes far than 180 degrees (I don't know why). That's why I am building my own code for that purpose.</p>
<p>I got it working just analyzing time consumption of digitalWrite and digitalRead functions. They took around 13us to execute (each one), so this added up a few extra undesired microseconds to the final period.</p> <p>Instead, I set up digital output using DDRD for configuring and PORTD for setting the desired output, which results in approximately 1us to set the output value (HIGH or LOW).</p> <p>I changed the prescaler to 8 and the code below shows how to get a 100kHz wave output with 5us duration of "on" time using timer1 CTC mode.</p> <pre><code>void setup() { DDRD = B00001000; // pin 3 as output PORTD &amp;= ~_BV(PORTD3); // set 3 as LOW // initialize Timer1 cli(); // disable global interrupts TCCR1A = 0; // set entire TCCR1A register to 0 TCCR1B = 0; // same for TCCR1B // set compare match register to desired timer count: OCR1A = 9; // turn on CTC (Clear Timer on Compare Match) mode: TCCR1B |= (1 &lt;&lt; WGM12); // Set CS10 bit for clk/8 prescaler: TCCR1B |= _BV(CS11); // Output Compare A Match Interrupt Enable TIMSK1 |= (1 &lt;&lt; OCIE1A); sei(); // enable global interrupts } ISR(TIMER1_COMPA_vect) { PORTD = ~PORTD; } </code></pre>
10391
|arduino-uno|arduino-ide|ide|
How can I use a 'Global' class object?
2015-04-28T00:31:01.497
<p>I created a class inside the sketch file(not in another file) and init it as object before setup() and loop() as a global object, after I change some parameters inside the object in setup() , I found in loop() the parameters in the global object remain unchanged. Here is the pseudocode code to describe my question:</p> <pre><code>//all of the code below are in the same ino file. class Animal{ public: bool alive = false; Animal (bool liveStatus){ alive = liveStatus; } } Animal dog(false); Animal cat(false); Animal lion(false); Animal animalArray(dog,cat,lion); void setup(){ for (int i=0;i&lt;3;i++){ Animal current_animal = animalArray[i]; current_animal.alive = true; } //here when I print each animal's alive flag is 'true' } void loop(){ for (int i=0;i&lt;3;i++){ // here the alive flag of each animal is still false , they should be all true!! } } </code></pre> <p>It looks like after I quit setup() somehow every change of the global object inside the setup are all gone .</p> <p>Thanks for helping me .. </p>
<p>Your problem here is that <code>Animal current_animal = animalArray[i];</code> is making a whole new Animal object that starts as a copy of <code>animalArray[i];</code>, but after that the two are no longer associated. Then when you call <code>current_animal.alive = true;</code>, you are not actually changing the animal in <code>animalArray[i]</code> anymore.</p> <p>The simplest way to fix this is to make <code>current_animal</code> a reference to the object you pick out of the array, although a pointer would work the same way. With this code:</p> <pre><code>Animal&amp; current_animal = animalArray[i]; current_animal.alive = true; </code></pre> <p><code>current_animal</code> becomes a reference to <code>animalArray[i]</code>, instead of a copy. Then operating on <code>current_animal</code> changes the same data that is stored in <code>animalArray[i]</code> like you intend.</p>
10392
|arduino-uno|pins|
Arduino Standalone - photo shows incorrect pin wired to MOSI
2015-04-28T01:37:44.677
<p>I have been building a standalone Arduino on a breadboard following the guide, <a href="http://www.arduino.cc/en/Main/Standalone" rel="nofollow noreferrer">Building an Arduino on a Breadboard</a>. The guide is generally very good, however, I have yet to get the Arduino working, for a number of various reasons, be it misinterpreted, or misread instructions (the reset pull-up resistor connected to GND instead of Vcc, Tx to Tx, instead of Tx to Rx (and vice versa), to name but a few issues that I have had to resolve). However, I am sure that the following issue is not down to my careless interpretation or lack of attention.</p> <p>Look at <a href="http://arduino.cc/en/uploads/Main/arduinobload_wires.jpg" rel="nofollow noreferrer">the photo</a> taken from the webpage, <a href="http://www.arduino.cc/en/Main/Standalone" rel="nofollow noreferrer">Building an Arduino on a Breadboard</a>, on the Arduino website, showing the <em>Sparkfun AVR programming adapter</em> connected to the ATmega IC. </p> <p><img src="https://i.stack.imgur.com/bQWqz.jpg" alt="Standalone Arduino breadboard"></p> <p>The MOSI on the adapter is shown to be connected, via a dark green wire, to pin 16 on the ATmega chip, whereas the instructions say:</p> <blockquote> <p>Be sure to refer to the Arduino pin mapping for help wiring this up.</p> <ul> <li>The MISO pin of your adapter will go to pin 18 or Arduino digital pin 12 of your Atmega chip.</li> <li>The SCK pin of your adapter will go to pin 19 or Arduino digital pin 13 of your Atmega chip.</li> <li>The RESET pin of your adapter will go to pin 1 of your Atmega chip.</li> <li>The MOSI pin of your adapter will go to pin 17 or Arduino digital pin 11 of your Atmega chip.</li> </ul> </blockquote> <p>According to the pinout below, Pin 16 is SS and pin 17 is indeed MOSI.</p> <p><img src="https://i.stack.imgur.com/PdcP5.png" alt="ATmega168 pin out"></p> <p>So, to my mind, the photo is definitely wrong. Indeed I was getting avrdude errors when trying to use a USBasp to load a bootloader, when using the wiring as shown in the photo. When I correctly wired MOSI, from the adapter, to pin 17, the avrdude errors disappeared.</p> <p>Am I correct in my thinking? Has anyone else attempted to build this circuit, following the instructions on the Arduino website, and come across this issue?</p> <p>I am just looking for confirmation that I am right, before I contact the owner of the web page.</p>
<p>I have programmed AVR microcontrollers for a while. I would follow the datasheet, instead of the guide you have.</p> <p>The Atmega168 Pin Mapping shows SS on 16, MOSI 17, MISO 18, SCK 19 and you will also need to connect to RST 1</p>
10401
|arduino-uno|c|string|
Problems splitting a string to get authentication and command
2015-04-28T11:56:42.953
<p>Good afternoon,</p> <p>In a nutshell I'm having some difficulty with splitting and returning part of a string.</p> <p>Essentially I'm working on the code for transmitting a password (24 character string) and command (string) in a single packet. However, the 'get_command' function is only returning the first character of the string (T) as opposed to the whole string (T1) and I'm not sure why. Any help would be greatly appreciated. Thanks in advance. </p> <p>The entire sketch is below so you should be able to just drop it in and compile.</p> <pre><code>char *received_data = "KkV3vKvLgC4PdBZRs5kkKM86T1"; char *password = "KkV3vKvLgC4PdBZRs5kkKM86"; int authenticate_transmission(char *data) { if(strncmp(data, password, 24)) { Serial.println("no match"); return false; } else { Serial.println("match"); return true; } } char *get_command(char *data) { char command[3]; strncpy(command, data + 24, 3); // Fine here Serial.println(command); return command; } void setup() { Serial.begin(9600); } void loop() { // test received data - message is T1 at the end. if (authenticate_transmission(received_data)) { char *command = get_command(received_data); // But just prints out first char when returned from a function Serial.println(*command); } delay(10000); } </code></pre>
<p>The direct issue is you have a dereference operator (<code>*</code>) in the loop that you don't need:</p> <pre><code>Serial.println(*command); </code></pre> <p>This causes it to pass <strong>only the first character</strong> to <code>Serial.println()</code> instead of the pointer to the memory location. That's the first issue.</p> <p>Like Peter mentioned, the string gets deallocated when returned from the <code>get_command()</code> function. It's undefined behavior, but it's luck that it worked the way it did.</p>
10403
|arduino-mega|remote-control|
Arduino R/C compatible transmitter and reciever
2015-04-28T12:21:53.943
<p>I want to make a RC buggy or something down those lines (using Legos of course) and I'm confused while looking what transmitter/receiver to use. Would like a simple classic remote and any compatible receiver for the Arduino. Found such a remote: <a href="http://www.hobbypartz.com/79p-th9x-r9b-9channel-radio.html" rel="nofollow">http://www.hobbypartz.com/79p-th9x-r9b-9channel-radio.html</a> But this seems way overkill for what I want to do. Any links or suggestions would be appreciated. Hope the question isn't too broad for stack exchange.</p>
<p>If you want to involve an Arduino on the receiver, you may want to choose a transmitter which is compatible with a 2.4 GHz chipset that is both available, and for which you can find Arduino code. The NRF24L01+ and Beken compatibles are probably the most available, and a lot of RC toys use something compatible, though getting firmware right to interact with them can be tricky. Beware that there are some other chips in wide use too, which can be harder to source a module for.</p> <p>You can use an off-the-shelf multi-channel receiver, but that will tend to output each channel on a distinct PWM pin, which is annoying if you want to capture the data into an Arduino.</p> <p>You might want to spend some time looking on rcgroups and in various hobby drone sites - the latter folks have a similar problem, as they want to collect all the control channels and mediate them through a custom flight computer (which in the early days was sometimes Arduino-compatible).</p> <p>You can also make your own transmitter - perhaps by retrofitting an NRF24L01+ module and miniature Arduino equivalent into the casing of an older 5/72/75 MHz set - or the IR transmitter from a toy helicopter.</p>
10411
|arduino-uno|power|
Powering arduino uno from Car's reverse light?
2015-04-28T22:20:30.777
<p>I am making a reverse sensing alarm system. I am using a HC-SR04, arduino UNo and a piezo buzzer. The programming was a success however i will like this circuit to be powered when the reverse gear is shifted into place. So I am thinking to power the V in of the UNO with the 10V from the reverse bulb socket receives. However I think the amperage sent to this bulb is too much for my UNO. What should I do ? and Does anyone have any other recommendations to power the UNO in such a scenario? </p>
<p>Power the Arduino in parallel with the bulb. Take the V+ wire running to the reverse light and the frame ground. The frame ground is any bare metal surface of your car will be grounded, just connect a wire to your frame. Or you can just splice the light bulbs ground wire. When powering the circuit in parallel you do not have to worry about the amperage draw of the light. By a barrel jack connector like <a href="https://www.sparkfun.com/products/10287" rel="nofollow">this connector from spark fun</a> you can buy these cheaper elsewhere just a 2.1mm barrel jack connector. Connect the positive and negative respectively, and connect the 12v into the Arduino's barrel jack. </p> <p>As a side note the bulb should be getting 12V not 10V it's not a huge problem, but it is a slight issue that could later be a problem or be caused by an electrical bug. If everything works don't scramble to fix it, but be aware it exists.</p>
10415
|atmel-studio|
Can I use a UDOO as an Arduino?
2015-04-29T00:44:03.387
<p>I have a UDOO, and I wonder whether or not it is possible to use the Arduino that it has without starting the UDOO's operating system, i.e., I would like use Atmel Studio to load a program within the Arduino at UDOO.</p>
<p>Yes, but you have to erase the flash (and reset the ATMEL SAM3X8E processor) manually before the programming. You can use the J16 and J22 jumpers to do this.</p>
10420
|arduino-uno|programming|power|motor|
Not sure if programmer or ATMega is burned
2015-04-29T10:52:11.847
<p>some time ago i tried doing <a href="https://www.youtube.com/watch?v=CMz2DYpos8w" rel="nofollow">this</a> with my original arduino uno r3. I guess i had to plug the power cables in wrong order(i think it's called reversing polarity) because my arduino stoped working. It turns on (the power diode is on) but i cannot upload any sketch on it. I'm thinking about changing the ATMega chip but, before i do that i want to be certain that it's the chip issue ,not the programmer. I have another arduino uno, and i heard that i can upload sketch with it to another uno. So my idea is, if i do this i will be able to say whether it's the programmer or the chip issue. The only problem is that i don't know how to do this and i wasn't able to find any reasonable tutorials online. Please tell me what to do. Many Thanks, Jan</p>
<p>The Arduino IDE ships with a built in <code>ArduinoISP</code> sketch, and there is a very detailed <a href="http://www.arduino.cc/en/Tutorial/ArduinoISP" rel="nofollow">tutorial</a> with wiring diagrams etc on the Arduino site.</p>
10427
|audio|
Electret microphone amplification
2015-04-29T16:34:41.440
<p>I've got an electret microphone and I understand that I need quite some amplification to get it to be read by an Arduino (0-5V input). So I seeked the web, but answers are as different as people on the street. Some use Op-Amps, some only a transistor cicruit or the like. This guy is using 2 amps before and after his filters <a href="https://www.youtube.com/watch?v=hpMVG4a9sR4&amp;feature=youtu.be" rel="nofollow">Video</a>, <a href="http://wiring.org.co/learning/basics/microphone.html" rel="nofollow">LM386</a> and this guy claims, that exactly this amp isn't good for the job: <a href="https://arduinodiy.wordpress.com/2012/12/20/electret-microphone-amplifier/" rel="nofollow">recommends NOT using LM386</a>.</p> <p>I really only want to have a threshold switch, so I need no filters whatsoever and not a super duper amplification. What is the simplest solution, with which I can read a voltage with the arduino? With a transistor alone (seems easiest to me so far) - how can I know how much it amplifies (or as I understand it modifies the "other voltage" to look the same)?</p> <p>I found many different schematics using various op-amps, but regarding them I don't really need another tutorial, but rather a rule of thumb for a "readable" amplification. Is 100 times enough? I found circuits with 1000 times amplification, so I'm really wondering which one works fine.</p> <p>However the really simple thing would be this: <a href="https://www.youtube.com/watch?v=0E9DzgRuL_k" rel="nofollow">video at 17sec</a>. At second 17 and 50 or so, they show an extremly basic circuit, which would be exactly what would work best for me... However the question is, if this is enough amplification for the ADC in an arduino.</p> <p>If I can't get a satisfying answer I think I'll build both and see how they compare/work for me.</p>
<p>I've built </p> <p><img src="https://i.stack.imgur.com/ceEoB.jpg" alt="Inverting Op-Amp"></p> <p>This circuit without C4 and everything after R4 (no rectifier, not a single diode used). R4 has to be switched for 100kOhms, since this gives a 100x amplification. I guess this is simple enough for most people. Thanks for the hints.</p> <p>The following code can be used to detect claps/noises. It is restricted to a double-clap with silence in between. Parameters can be easily tuned. This works quite well for me, even when I play noise/TV/music to the speaker directly it triggers rarely, or not at all!</p> <pre><code>// CLAP switch using an electret microphone // switches ie. a relais or led with a certain // clap-melody // sound parameters const int THRESHOLD = 20; const int VAL_MEAN = 507; // trigger characteristics const int CLAPS_TO_TRIGGER = 2; // number of claps const int DEBOUNCE_TIME = 150; // ms to ignore double-clapping const int SILENCE_T = 40; // ms between claps, otherwise reset const int MELODY_INTERVAL = 800; // ms max time for the claps const int PAUSE_TIME = 2000; // wait after switch, or noise // pin-layout const int analogPin = 0; const int OUTPUT_PIN = 13; int output_state = LOW; uint32_t pause_t = 0; uint32_t debounce_t = 0; uint32_t start_time = 0; // timestamp of first clap-start uint8_t claps = 0; int sensorVal = 0; int amp = 0; void setup() { Serial.begin(115200); pinMode(OUTPUT_PIN,OUTPUT); } void loop() { sensorVal = analogRead(analogPin); amp = abs(sensorVal-VAL_MEAN); // Serial.print(F("sensed: ")); Serial.println(sensorVal); // Serial.print(F("amp: ")); Serial.println(amp); // at the end of an interval check the number of claps if (millis()-start_time &gt; MELODY_INTERVAL &amp; claps != 0) { if (claps == CLAPS_TO_TRIGGER &amp; millis()-pause_t &gt; PAUSE_TIME) { output_state = !output_state; pause_t = millis(); digitalWrite(OUTPUT_PIN,output_state); Serial.print(F("Triggered ")); Serial.println(output_state); } if (claps&gt;CLAPS_TO_TRIGGER) { Serial.print(F("- too many")); } reset(); } // noise/clap detected if (amp &gt; THRESHOLD &amp;\ millis()-debounce_t &gt; DEBOUNCE_TIME &amp;\ millis()-pause_t &gt; PAUSE_TIME) { // there has to be silence between claps if (millis()-debounce_t &lt; SILENCE_T+DEBOUNCE_TIME) { claps = 0; debounce_t = millis(); Serial.print(F("reset - silence interrupted")); Serial.print(F(" amp "));Serial.println(amp); } else { claps++; debounce_t = millis(); Serial.print(F("claps "));Serial.print(claps); Serial.print(F(" amp "));Serial.println(amp); if (claps == 1) { start_time = debounce_t; } } } delay(1); } void reset() { // time has expired start_time = 0; claps = 0; debounce_t = 0; Serial.println(F("reset")); } </code></pre>
10431
|hardware|
What are the advantages of "Arduino compatible" boards
2015-04-29T19:59:20.550
<p>There are countless boards called <a href="http://en.wikipedia.org/wiki/List_of_Arduino_boards_and_compatible_systems" rel="nofollow">"Arduino compatible board"</a>. Some of them have specialized hardware features such as WiFi, SD card readers etc., but most of them seem like plain Arduino copies to me.</p> <p>Sure, they are a bit cheaper, but for me the price difference doesn't make me favor the money I'd safe over the potential issues I have yet to discover.</p> <p><strong>Question:</strong> What are the benefits (or disadvantages) of Arduino compatible boards <em>(the ones without the "extras")</em> in general? Do you know an Arduino compatible board that you would recommend for some extraordinary features?</p>
<p>While Arduino is an open source system, "Arduino" is a trademarked name and may only legally be used for products from the Arduino's originators or licensed suppliers. Arduino are quite clear about this requirement - <a href="http://www.arduino.cc/en/Trademark/CommunityLogo" rel="nofollow"><strong>see here - Logo</strong></a> and here <a href="http://www.arduino.cc/en/Trademark/HomePage?from=Main.Trademark" rel="nofollow"><strong>Trademark</strong></a> and here <a href="http://www.arduino.cc/en/Main/Policy" rel="nofollow"><strong>What makes an Arduino board an Arduino?</strong></a> and <a href="http://www.arduino.cc/en/Main/FAQ" rel="nofollow">FAQ</a></p> <p>As a result, compatible microcontroller boards are legally required to NOT identify themselves as being "Arduinos", so the term "Arduino compatible" is about the most that even an Arduino-identical clone can claim. </p> <hr> <p>As karan notes, some Chinese sourced Arduino compatibles "have issues".<br> however, I have had no problems at all with Arduino compatibles manufactured and supplied by <a href="http://www.aliexpress.com/store/812021/search?SearchText=nano" rel="nofollow"><strong>this Chinese supplier</strong></a>. As well as the basic devices they sell various interface boards (shields) and related equipment. Prices are astoundingly low, free postage is included in many cases (about 2 to 3 weeks delivery time to New Zealand) or you can pay for courier delivery. I buy Nano or Pro-Mini compatibles devices - usually in batches of 10. As you will see - Nano compatible costs $US3 each in 10's. Pro Mini compatible is currently $US1.68 each in 10's. !!!<br> Uno compatible <a href="http://www.aliexpress.com/store/812021/search?SearchText=arduino" rel="nofollow"><strong>here</strong></a> is $3.80 in 10s. The voltage requlator may be a different type than than on 'real' Arduinos (but work OK) and versions with a USB-serial bridge IC use a non FTDI IC and you need to source and load the correct (freely available) drivers. </p> <p>NB: (1) I have NO commercial connection with this company except as a very happy customer.<br> (2) I'd expect you to have no problems with these or other products from them but I of course have no responsibility for what they sell.</p>
10440
|arduino-uno|usb|
How to use an Arduino Uno + Keyboard Firmware to make a "N Key Rollover" Game Pad
2015-04-30T08:06:29.613
<p>Hello I have flashed my Arduino Uno with USB keyboard firmware from this tutorial <a href="http://mitchtech.net/arduino-usb-hid-keyboard/#comment-6786" rel="nofollow">http://mitchtech.net/arduino-usb-hid-keyboard/#comment-6786</a>, and I have been successful sending individual key presses but, not when trying to press an hold a key. I am attempting to use this firmware to create a custom Game Pad to USB adapter, the only issue is sending simultaneous keystrokes (not sending them one at a time). If you know how to accomplish this task I would be very happy. The technical term for this is "Key Rollover" </p>
<p>Could you post an example of your updated code? I'm working on a similar project but a complete n00b as far as using the Arduino goes.</p>
10441
|shields|bluetooth|
Android Studio project for Redbearlab BLE Shield apps
2015-04-30T08:59:51.217
<p>To interact with its <a href="http://redbearlab.com/bleshield/" rel="nofollow">BLE shield</a>, Redbearlab published sample Android apps in the Play Store. The sources for the apps are available on <a href="https://github.com/RedBearLab/Android" rel="nofollow">GitHub</a>. How can I build them in Android Studio?</p>
<p>It was much simpler than expected to put together the Android Studio projects. They are on <a href="https://github.com/ryklith/RBL_for_Android_Studio" rel="nofollow">GitHub now</a>.</p> <p>Note that the apps built from source are actually different from the ones published by Redbearlabs on the Play Store. On top of that, the chat app is not working.</p>
10444
|arduino-uno|programmer|
Is it possible to program Arduino UNO with USB/TTL adapter withouth connection Vcc
2015-04-30T12:43:11.153
<p>For some strange reason my Arduino UNO clone board occasionally cause my Mac to reset, when I connect the usb cable. Possibly a power problem in Arduino or the USB hub. </p> <p>Is it possible to program Arduino UNO with USB/TTL adaptor withouth conncecting the Vcc and GND pins (RX/TX and DTR only.)</p>
<p>It is a bit of work, but it is possible to use a couple of optoisolators to <A href="http://www.nerdkits.com/forum/thread/2040/" rel="nofollow noreferrer">build a circuit that will electrically isolate the MCU from the serial adapter</a>.</p> <p><img src="https://i.stack.imgur.com/3fGYZ.jpg" alt="optoisolator circuit"></p> <p>You should still figure out why your computer resets though, as it may not be related to the Arduino at all (e.g. maybe the cable is bad).</p>
10451
|library|ethernet|
Can I use custom ethernet shield with standard libraries?
2015-04-30T22:41:10.633
<p>I would like to make a custom ethernet card that uses the enc28j60 like this: <a href="http://www.picprojects.net/enc28j60_modul/index.html" rel="nofollow">DIY Ethernet card</a></p> <p>but first I would like to know if I can use the standard libraries which can be used with the ethernet card which is in the market like this: <a href="http://www.ebay.co.uk/sch/i.html?_from=R40&amp;_trksid=p2047675.m570.l1313.TR0.TRC0.H0.XENC28J60%20module.TRS0&amp;_nkw=ENC28J60%20module&amp;_sacat=0" rel="nofollow">ENC28J60 ethernet module</a></p>
<p>The libraries don't care whether or not you're using a shield, only that you're using a device they support and that you've wired it up how they expect (or that you've modified the library to use the actual wiring you're using). So find a library that supports the ENC28J60 and knock yourself out.</p>
10457
|ethernet|
Ask for available ip on ethernet shield
2015-05-01T02:24:11.193
<p>Is there any way so an ethernet shield to ask the router for an available ip address? For example to ask for an ip an the router to return 192.168.1.2 if it is available. I am asking it because if we set the ip programmatically and it is attached to another device we gonna have problem. </p>
<p>Using the <a href="http://en.wikipedia.org/wiki/Dynamic_Host_Configuration_Protocol" rel="nofollow">DHCP (Dynamic Host Configuration Protocol)</a> you can obtain an IP address dynamically from a DHCP server (which a router usually also is), without having to hardcode it into the firmware of the Arduino, thus enabling it to work on different networks.</p> <p>There is also a library for that: <a href="http://www.arduino.cc/en/Tutorial/DhcpAddressPrinter" rel="nofollow">http://www.arduino.cc/en/Tutorial/DhcpAddressPrinter</a>. It's an extension of the official Arduino Ethernet library, written for the Arduino Ethernet Shield, but you'll likely find implementations of DHCP in many Ethernet libraries (I am using the <a href="https://github.com/jcw/ethercard" rel="nofollow">EtherCard library</a>) because it's an important feature to be able to connect to a network without a statically assigned IP and "only" requires UDP (on top of IP).</p> <p>For e.g. the Ethernet library you call the <a href="http://www.arduino.cc/en/Reference/EthernetBegin" rel="nofollow"><code>begin</code> function</a> either with only the MAC address of your device or with MAC and IP address: </p> <pre><code>Ethernet.begin(mac); Ethernet.begin(mac, ip); </code></pre> <p>In the first case it will use DHCP to obtain an IP address dynamically, in the second case it will use the static IP address you provide. Be warned that the second case, due to the needed implementation of DHCP, will increase the size of the compiled binary significantly. </p>
10458
|shields|
What options are available for connecting to a CDMA network?
2015-05-01T02:39:48.267
<p>I am looking specifically to connect to a CDMA carrier from an Arduino. In doing research, I came across a CDMA shield option (requires getting a <a href="https://www.nimbelink.com/2g-cdma-1xrtt/" rel="noreferrer">CDMA module</a> that you drop <a href="https://www.nimbelink.com/skywire-arduino-cellular-shield/" rel="noreferrer">into a shield</a>), but that ends up being quite expensive - the CDMA module alone is $140, as opposed to a GSM shield which runs $30-$60. I've also tried looking for other CDMA modules, but haven't been able to find much.</p> <p>Even if it's not sold as a proper Arduino shield, does anyone know of a CDMA module for hobby projects?</p>
<p>I am looking at NimbeLink's Arduino baseboard which works with a CDMA modem. Never tried it, but thinking of ordering one. <a href="http://nimbelink.com/skywire-arduino-cellular-shield/" rel="nofollow">http://nimbelink.com/skywire-arduino-cellular-shield/</a>. Not sure if you'd put this as 'affordable' since it is $40 for baseplate + $130 for modem.</p> <p>Also this Arduino WCDMA 3G. <a href="http://linksprite.com/wiki/index.php5?title=3G_%2B_GPS_Shield_for_Arduino" rel="nofollow">http://linksprite.com/wiki/index.php5?title=3G_%2B_GPS_Shield_for_Arduino</a></p> <p>Frustrating to have all this cheap awesome GSM technology, but only CDMA network in my region. </p>
10483
|power|led|pins|pwm|mosfet|
MOSFET to dim LED backlight
2015-05-02T08:07:40.360
<p>I have built the following to dim the brightness of the LED backlight of a display: <img src="https://i.stack.imgur.com/T3KtX.png" alt="enter image description here"> I am using a BS170 MOSFET (the diode is no extra part but included in the MOSFET, according to the <a href="https://www.fairchildsemi.com/datasheets/BS/BS170.pdf" rel="nofollow noreferrer">datasheet</a>). The BL pin is the supply of the LED backlight. (I have left out all other pins.)</p> <p>Unfortunately, it does not work. Even if I set the PWM pin to 255, the backlight does not light (actually it's completely off). If I short BL and Vcc, it lights up as it should. </p> <p>Also, the voltage readings confuse me: I measure 3.3 V on the gate and drain against ground, 1.5 V on source against ground (= the voltage across the backlight) but only 1 V if I measure drain against source. </p> <p>So my questions are: </p> <ol> <li>Shouldn't this add up to 3.3 V?</li> <li>More importantly, why do I get only 1.5 V at BL?</li> <li>Most importantly, what do I need to change? Different MOSFET? No MOSFET?</li> </ol> <p>The primary aim of controlling the backlight is to be able to switch in off completely, thus reducing power consumption. (Being able to dim it is only a plus.)</p> <h2>EDIT</h2> <p>I should have added details about the display. It's one of those: <img src="https://i.stack.imgur.com/dP3Uh.jpg" alt="enter image description here"></p> <p>I haven't found a datasheet / specs for exactly this model. Most datasheets I found refer to a different version that is not 5 V compatible. A very similar model is described <a href="http://skpang.co.uk/catalog/images/lcd/graphic/docs/User_Manual_ET_LCD5110.pdf" rel="nofollow noreferrer">here</a>.</p> <p>Concerning my question I haven't found information on how much current the backlight would draw. Therefore I didn't want to drive it directly from the PWM pin. (Actually I could just measure it...)</p>
<p>Since you are switching on the high side, you need a P-channel mosfet, not an N-channel like the BS170. (Or you need a higher voltage on the Gate to reach the V<SUB>GS(th)</SUB>).</p> <p>I have a similar display, but mine will light up if BL is connected to ground. For these kind of displays you'd use a N-channel mosfet.</p>
10485
|interrupt|signal-processing|isr|frequency|
Making a composite waveform using a single TIMER interrupt
2015-05-02T09:48:05.750
<p>I'm writing software for a laser tag gun, which under the system we use needs the output waveform to be a carrier wave of 57600Hz with a signal wave of 1800HZ for about 50ms</p> <p>Using the Tone library (<a href="https://code.google.com/p/rogue-code/wiki/ToneLibraryDocumentation" rel="nofollow">https://code.google.com/p/rogue-code/wiki/ToneLibraryDocumentation</a>) and a transistor AND gate, I've had this working using two timers, however I really want to shrink it down to one timer so that I can use the other for sound (using the TMRPCM library which only needs timer1). </p> <p>I've modified the Tone library cut down to what I need, with the following methods:</p> <pre><code>void TagTone::beginPulse(uint8_t tonePin) { _pin = tonePin; _timer = 2; // 8 bit timer TCCR2A = 0; TCCR2B = 0; bitWrite(TCCR2A, WGM21, 1); bitWrite(TCCR2B, CS20, 1); timer2_pin_port = portOutputRegister(digitalPinToPort(_pin)); timer2_pin_mask = digitalPinToBitMask(_pin); int duration = 50; //50 milliseconds uint8_t prescalarbits = 0b001; int32_t signal_toggle_count = 0; // Note: may need prescaler reimplemented if using 16Mhz, fine on current 8Mhz ocr = F_CPU / (CARRIER_FREQUENCY * 2) - 1; prescalarbits = 0b001; TCCR2B = (TCCR2B &amp; 0b11111000) | prescalarbits; toggle_count = 2 * CARRIER_FREQUENCY * duration / 1000; // how many times the carrier toggles before pulse ends // want to AND with 1800 Hz signal // as duration now set to 50: toggle_count for carrier = 5760 // equivalent toggle count for signal = 180 signal_toggle_count = 2* SIGNAL_FREQUENCY * duration / 1000; // want to flip signal state every 32 carrier pulses signal_cycle_count = 32; //toggle_count / signal_toggle_count; } // duration (in milliseconds). void TagTone::playPulse() { OCR2A = ocr; timer2_signal_toggle_count = signal_cycle_count; timer2_toggle_count = toggle_count; bitWrite(TIMSK2, OCIE2A, 1); } ISR(TIMER2_COMPA_vect) { if(timer2_toggle_count &lt; 0) { *timer2_pin_port ^= timer2_pin_mask &amp; signal_state; // flip if (timer2_signal_toggle_count &gt; 0) { timer2_signal_toggle_count--; } else { signal_state ^= signal_state; timer2_toggle_count -= timer2_signal_toggle_count; timer2_signal_toggle_count = signal_cycle_count; } } else { TIMSK2 &amp;= ~(1 &lt;&lt; OCIE2A); // disable the interrupt *timer2_pin_port &amp;= ~(timer2_pin_mask); // keep pin low after stop } } </code></pre> <p>What I hope this is doing is 32 toggles at the carrier speed (ie 16 full cycles of 57600Hz), followed by 32 'silent' toggles where nothing happens, followed by another 32 at carrier speed, etc. I should then be able to fire using:</p> <pre><code>digitalWrite(signalPin, HIGH); carrierTone.playPulse(); delay(60); digitalWrite(signalPin, LOW); </code></pre> <p>But that doesn't set off the sensor, whereas the simple code below works.</p> <pre><code>carrierTone.play(57600, 50); signalTone.play(1800, 50); </code></pre>
<p>Woo, solved it. My ISR code was completely wrong. Works using:</p> <pre><code>ISR(TIMER2_COMPA_vect) { if (timer2_signal_toggle_count != 0) { // toggle the pin if(signal_state == 1) *timer2_pin_port ^= timer2_pin_mask; if (timer2_toggle_count &gt; 0) timer2_toggle_count--; else { TIMSK2 &amp;= ~(1 &lt;&lt; OCIE2A); // disable the interrupt *timer2_pin_port &amp;= ~(timer2_pin_mask); // keep pin low after stop } timer2_signal_toggle_count --; } else { timer2_signal_toggle_count = signal_cycle_count; timer2_toggle_count --; if(signal_state == 1) { signal_state = 0; *timer2_pin_port &amp;= ~(timer2_pin_mask); //*timer2_pin_port ^= timer2_pin_mask; } else { signal_state = 1; *timer2_pin_port ^= timer2_pin_mask; } } } </code></pre> <p>I was trying to just AND the signal state into the original pin state, which was completely the wrong thing to do.</p>
10489
|arduino-uno|
Arduino uno r3 not powering up
2015-05-02T14:01:03.950
<p>i bought two arduino uno r3 card (not original) one is working perfectly: <img src="https://img11.hostingpics.net/pics/6526993911.jpg" alt="1" /> the other is not powering up (no led is lit), i did some measuring and i found that two usb connector pins on the board are shorted, how can i proceed to repair it taking in account that it works from time to time ! <img src="https://img11.hostingpics.net/pics/217640602.jpg" alt="2" /> thank you More images: <img src="https://s11.postimg.org/6ukiv3khf/SAM_1434.jpg" alt="3" /></p> <p><a href="https://i.stack.imgur.com/tgYhM.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tgYhM.jpg" alt="4" /></a></p>
<p>It looks as though there may be material between at least one USB pin and the ground layer. This may be flux of solder 'splash'.</p> <p>If visual inspection shows that this may be the case I would try <strong>carefully</strong> scratching with a sharp poibt (eg scriber) along at least the green arc on the image below. Be careful not to break intended conduction paths (eg as shown in black).</p> <p><img src="https://i.stack.imgur.com/AZ38r.jpg" alt="enter image description here"></p>
10496
|arduino-uno|shields|hardware|
Picking an Arduino
2015-05-03T04:37:18.237
<p>I'm looking to develop my own personal SmartWatch, hardware, software, and all. My problem is starting off on the hardware portion of it; more specifically what platform I should build it on. I already have an Arduino Uno (R3), nut I was hoping to find something a bit smaller. Any recommendations on what parts I should use?</p>
<p>Have a look at the LilyPad (<a href="https://www.arduino.cc/en/Main/ArduinoBoardLilyPad" rel="nofollow noreferrer">Main Board</a>, <a href="https://www.arduino.cc/en/Main/ArduinoBoardLilyPadUSB" rel="nofollow noreferrer">USB</a>, <a href="https://www.arduino.cc/en/Main/ArduinoBoardLilyPadSimple" rel="nofollow noreferrer">Simple</a>) and <a href="https://www.arduino.cc/en/Main/ArduinoGemma" rel="nofollow noreferrer">Gemma</a>. The Gemma may have too few I/O pins for your needs, but it really does look small.</p>
10501
|arduino-uno|motor|transistor|
Transistor for DC motor and 9v
2015-05-03T11:17:24.247
<p>I have this schematic for a DC motor in my arduino, now I want to add 9v battery.</p> <p>But I've seen that people use TIP120 transistor, I have BC548B, can I just put the 9v with that transistor?</p> <p><img src="https://i.stack.imgur.com/7rYsX.png" alt="enter image description here"></p>
<p>Firstly, I see no external power supply in your schematic.<br> Secondly, you certainly CANNOT use a BC548 for controlling a motor.<br> MOSFETS are the best.</p>
10505
|arduino-uno|
New UNO, BLINK not working
2015-05-03T11:47:37.633
<p>Finally got around to playing with my uno today for the first time. ( It's a branded sunfounder UNO R3)</p> <p>First project. Simple blink. Using arduino 1.6.3, Windows 8.1 It is hooked up correctly.</p> <pre><code>void setup() { // initialize digital pin 13 as an output. pinMode(9, OUTPUT); } // the loop function runs over and over again forever void loop() { digitalWrite(9, HIGH); // turn the LED on (HIGH is the voltage level) delay(10000); // wait for a second digitalWrite(9, LOW); // turn the LED off by making the voltage LOW delay(10000); // wait for a second } </code></pre> <p>What I get is a fast blinking LED. I've tried multiple values and it doesn't change. No error on upload. I've commented out everything except the digitalWrite(9, HIGH); and I get a fast blink.</p> <p>I tried:</p> <pre><code>void loop() { digitalWrite(9, LOW); delay(5000); digitalWrite(9, HIGH); // turn the LED on (HIGH is the voltage level) } </code></pre> <p>And I get nothing, it doesn't even turn on.</p> <p>Same if I remove the first digitalWrite();</p> <p>So, I'm already a little lost here. I did a but of google searching tried adding a serial 9600 line, and a few other things. Nada.</p>
<p>Defective board. Thanks to @br1an for the milli idea. New board in the way, not a clone. </p>
10508
|arduino-uno|robotics|
Disassembling a RC car for a Arduino Robot
2015-05-03T17:06:33.773
<p>I am looking at making an Arduino robot car. I have a RC car( photos below). I was wondering if I could take the chassis of the car and modify it to make it Arduino controlled, if so how could I do that?(I have an Arduino UNO R3). I would like to make it into a wall avoiding robot. I have never soldered a thing in my life, and I don't own a soldering iron.</p> <p><img src="https://i.stack.imgur.com/fZtWO.jpg" alt="enter image description here"></p> <p><img src="https://i.stack.imgur.com/JL37f.jpg" alt="enter image description here"></p> <p><img src="https://i.stack.imgur.com/5GVaX.jpg" alt="enter image description here"></p> <p><img src="https://i.stack.imgur.com/wa7ho.jpg" alt="enter image description here"></p>
<p>Someone has done exactly this, and written detailed instructions at <a href="http://www.instructables.com/id/Autonomous-Control-of-RC-Car-Using-Arduino/" rel="nofollow">http://www.instructables.com/id/Autonomous-Control-of-RC-Car-Using-Arduino/</a></p> <p>Some remote control devices (usually not the really cheap ones, like the one shown here) will have a standard transmitter/receiver. See <a href="http://www.alibaba.com/product-detail/3-channel-radio-control-receiver-box_311659816.html" rel="nofollow">http://www.alibaba.com/product-detail/3-channel-radio-control-receiver-box_311659816.html</a> for a picture of the receiver. If you can find this in your remote control device, you should be able to unplug it, and replace it with an Arduino. You will need the "Servo" library - see <a href="https://www.arduino.cc/en/reference/servo" rel="nofollow">https://www.arduino.cc/en/reference/servo</a></p> <p>You can probably get away without soldering - you will probably need to strip some wires, and you can use crocodile clips, and/or breadboard jumpers to connect everything up. It won't be pretty.</p> <p>If you want to learn to solder (I know it's intimidating, but it's not so bad) I recommend that you find a local hackspace/makerspace, and find someone there - they will probably be more than happy to teach you. They probably have everything you need, be nice to them, and if you want them to continue, join up &amp; pay regular subs. And take every opportunity to teach the skills you have to anyone else who asks for help.</p>
10512
|led|resistor|
Why all blink tutorials use 330 ohm resistor
2015-05-03T18:53:40.663
<p>When I do the led calculation I found 150 ohm resistor is enough for 3mm red led. If so why all arduino tutorials, <a href="http://blog.grifby.com/2013/04/tutorial-1-blinking-led-using-arduino.html" rel="nofollow">like this one</a>, are suggesting 330 ohm resistor?</p> <p>I assume V = 5 Volt, diode forward voltage = 2V and diode forward current 20mA</p>
<p>An important consideration is that the chip cannot necessarily source 20 mA on all output pins at once. In fact pins D5 to D13 on the Uno (PD5 to PD7, and PB0 to PB5) cannot source more than 150 mA combined. Thus the maximum you could source on those pins, if you are driving them all at once, is 150 / 9 = 16 mA.</p> <p>So, designing for 10 mA per LED is allowing a safety margin, possibly to save tutorials the complexity of explaining that 20 mA is OK for one pin, but not for all the pins at once.</p>
10516
|rtc|
RTC square wave
2015-05-03T19:51:21.180
<p>I have a DS3231 Real Time Clock module and I'd like to use the Square Wave output. </p> <p>I wonder how can I set the frequency of the pulse?</p> <p>How long is the (time) length of the pulse?</p> <p><strong>UPDATED QUESTION</strong></p> <p>In order to use the DS3231 as an 1PPS interrupt, I want to use the Square Wave output. Here's how I connected it to an Arduino.</p> <p><img src="https://i.stack.imgur.com/yeJ10.png" alt="enter image description here"></p> <p>I connected to the SQW output a 10kΩ pull-up resistor and an LED. After that I tested the code which shows the time and worked fine. </p> <pre><code>#include &lt;Wire.h&gt; #include "RTClib.h" RTC_DS1307 rtc; void setup () { Serial.begin(9600); #ifdef AVR Wire.begin(); #else Wire1.begin(); #endif rtc.begin(); if (! rtc.isrunning()) { Serial.println("RTC is NOT running!"); rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); } } void loop () { DateTime now = rtc.now(); Serial.print(now.year(), DEC); // etc } </code></pre> <p><em>(The DS3231 works fine with the DS1307 library)</em></p> <p>In this case the LED was just flickering, so I thought that the default frequency of the SQW should be grater than 1Hz. I googled a bit and realized that I had to change some registers. So I found this piece of code which I called from the setup() function, but with no success, the LED is still flickering.</p> <pre><code>void set1Hz() { // Frequency is stored in register 0x0e in bit 3 and 4 Wire.beginTransmission(0x68); Wire.write(0x0e); Wire.endTransmission(); Wire.requestFrom(0x68, 1); uint8_t register0E = Wire.read(); // clear bits 3 and 4 for 1Hz register0E &amp;= ~(1 &lt;&lt; 3); register0E &amp;= ~(1 &lt;&lt; 4); // put the value of the register back Wire.beginTransmission(0x68); Wire.write(0x0e); Wire.write(register0E); Wire.endTransmission(); } </code></pre> <p>Since I'm now qualified for low level programming, any suggestions on how to change the registers would be appreciated.</p>
<p>SQWV output only pulls low, it is an open drain output.</p> <p>Wire up like this: 5V to LED anode, LED cathode to current limit resistor, other leg of resistor to SQWV pin.</p> <p>Check the current capability of the pin. 10K will make very dim (if seen at all) LED. Try 1K.</p>
10531
|arduino-uno|arduino-mega|hardware|
Arduino selection for RTOS
2015-05-04T15:25:11.430
<p>I am brand new to Arduino and am having a difficult time understanding the "lay of the land". I'm looking for the beefiest, fastest, most compute-centric Arduino available to the market that will run <a href="https://github.com/embox/embox" rel="nofollow">embox</a>.</p> <p>As I understand it, there is really only the Uno and the Mega, both of which are 32-bit. However I also believe that 64-bit variations/designs exist and was wondering if anyone has actually implemented Arduino Uno/Mega as a 64-bit MCU. I also see there is the Arduino Due, but not sure how that fairs (beefiness-wise) with Uno/Mega.</p> <p>So to summarize: <strong>What is the beefiest Arduino one can find, is it 32- or 64-bit, and will it run an embedded RTOS like embox?</strong></p>
<p>You could try an <a href="https://www.arduino.cc/en/ArduinoCertified/IntelEdison" rel="nofollow">Intel Edison Arduino Kit</a>.</p> <p>It's 64 bit and can be programmed with a variant of the Arduino IDE. You can interleave Arduino code with system calls to the Linux OS, depending on which approach better suits a specific need.</p> <p>Running an RTOS inside Edison seems a bit overkill, however it should be doable.</p> <p>Otoh you could just rely on the much higher clock to provide quasi-deterministic response.</p> <p>Or just ditch the Arduino IDE and write a normal program with your programming language of choice.</p>
10537
|arduino-due|
Arduino: ARM, MCU, SoC and RTOS
2015-05-04T16:56:45.047
<p>I'm trying to understand the relationship between embedded RTOSes, SoCs and chip architectures. Specifically, I have a hobby project that would involve me writing a real-time, embedded application for the <a href="https://github.com/embox/embox" rel="nofollow">embox RTOS</a>, and use Arduino hardware for my proof of concept/prototype. Then, budget permitting, I'd like to port that app to run on another, non-Arduino ARM-based system.</p> <p>My <em>understanding</em> is that ARM is the chip architecture (a conceptual design, really), and that Arduino simply implements this design, and is also a "system on a chip" because it has other things (USB ports, GPIO pins, etc.) that make it more of a computer than just a MCU.</p> <p>My <em>understanding</em> is that if embox runs on ARM, which they claim it does, then at some point in the future I can take my application and run it on another ARM-based system without any real headache/pain.</p> <p>Is my understanding of: ARM, Arduino, MCU, SoC and embox/RTOS correct? If not, please clarify/correct me! If so, what sort of considerations <em>would</em> have to be made when porting my app to another ARM system in the future?</p>
<blockquote> <p>My understanding is that ARM is the chip architecture (a conceptual design, really),</p> </blockquote> <p>ARM is the CPU core architecture used in the Atmel SAM3X MCU family. The MCU is the CPU plus all of the facilities (PWM, ADC, DAC, DMA, etc.) that are implemented in order to allow the CPU to interact with external circuitry.</p> <blockquote> <p>and that Arduino simply implements this design,</p> </blockquote> <p>Most appropriately, "Arduino" is the IDE and the software libraries that come along with it, plus the specifications and connector layout of the various pieces of Arduino hardware.</p> <blockquote> <p>and is also a "system on a chip" because it has other things (USB ports, GPIO pins, etc.) that make it more of a computer than just a MCU.</p> </blockquote> <p>"SoC" is exactly what it says on the tin: it's an entire system on a single chip. The Due is not a SoC, since it's a full board. The BCM2835 found on the RPi is a SoC. The SAM3X is a MCU, since it still requires more than just connectors to become a full "system".</p> <blockquote> <p>My understanding is that if embox runs on ARM, which they claim it does, then at some point in the future I can take my application and run it on another ARM-based system without any real headache/pain.</p> </blockquote> <p>Provided that embox runs on the new system and that your application can be compiled for it.</p>
10541
|interrupt|timers|avr|
AVR Timer1 OCR1A controls TIMER1_COMPB_vect interrupt!
2015-05-04T18:08:23.287
<p>I was struggling with timer interrupts in my project. I couldn't make it work properly. So I decided writing a simple code and I saw a very interesting case.</p> <pre><code>ISR(TIMER1_COMPB_vect) { PORTB ^= (1 &lt;&lt; PORTB5); } int main(void) { cli(); // disable global interrupts TCCR1A = 0; // set entire TCCR1A register to 0 TCCR1B = 0; // same for TCCR1B OCR1A = 10000; OCR1B = 100; TCCR1B |= (1 &lt;&lt; WGM12); TCCR1B |= (1 &lt;&lt; CS10); TCCR1B |= (1 &lt;&lt; CS12); TIMSK1 |= (1 &lt;&lt; OCIE1A); TIMSK1 |= (1 &lt;&lt; OCIE1B); DDRB= 0xFF; #define F_CPU 16000000 sei(); while (1) { } } </code></pre> <p>Here is my code. When I change OCR1B value, nothing happens, but if I change OCR1A value then blinking gets faster. Is there a logical explanation for this?</p>
<p>By setting WGM12, you set the time to CTC mode. In this mode the timer will restart when it reaches that value set to OCR1A. So the lower the value, the faster it restarts, so the higher the frequency.</p> <p>The OCR1B value only changes where in this cycle the interrupt occurs. It will however still only be called once per timer1 overflow.</p>
10543
|shields|battery|solar|
What connects to Arduino Solar Shield?
2015-05-04T18:47:11.873
<p>I see there is an <a href="http://www.ns-electric.com/products/energyshield/" rel="nofollow">Arduino EnergyShield</a> available, and am wondering what (specific) <strong>solar</strong> shield/panels/attachments can be used to power it. Thoughts?</p> <p>Bonus points if someone can explain how long the solar unit would take to charge the Energy Shield if the Arduino was on but idling (low-to-nonexistent power output).</p>
<p>First, panels that you can use...</p> <p>There are a few at Adafruit (<a href="https://www.adafruit.com/products/200" rel="nofollow">here</a>, <a href="https://www.adafruit.com/products/500" rel="nofollow">here</a> or <a href="https://www.adafruit.com/products/1525" rel="nofollow">here</a>)</p> <p>You just want to check that the barrel jack and plug are the same size. I couldn't find dimensions in the <a href="http://www.ns-electric.com/download/energyshield/energyShield%20-%20Product%20Manual.pdf" rel="nofollow">documentation for the energy shield</a> so you may need to dig a little deeper or just swap it for <a href="http://www.digikey.com/product-detail/en/PJ-035D/CP-035D-ND/1644534" rel="nofollow">one that you know will work</a>.</p> <p>Also, the question about how long it will take also depends. First, if we assume that the arduino is not running we can get ~500mA from the second solar panel listed. If we can get all of that into the battery, it would take (1200mAH/500mA) about 2.4 hours to fully charge the battery. It looks like you have to make some adjustments on the shield to get the most out of your solar panel. And of course, you'll want to adjust those calculations based on the panel that you end up getting.</p> <p>Now, if we assume the Arduino is running <a href="http://forum.arduino.cc/index.php?topic=5536.0" rel="nofollow">and consuming about 25mA</a> you will have to subtract that 25mA from the 500mA that the solar panel is providing. So, in general...</p> <p>**</p> <blockquote> <p>(Battery Capacity)/(Solar Panel Current - Arduino Current) = Charge Time.</p> </blockquote> <p>**</p> <p>And you have a lot of control over the solar panel current and the arduino current based on the exact arduino that you use, etc, etc.</p> <p>There is also probably some loss regulating the solar panel voltage from 5-6V down to charge the battery (which is probably at 3.7V). I also don't know if the charging circuitry will limit the amount of current going to the battery.</p> <p>Take Away: There's a lot of stuff to consider when trying to answer this question. I think your best bet would be to get a panel that fits and dump the fuel gauge values out to the console every few minutes.</p>
10551
|arduino-uno|ethernet|communication|
MQTT vs Tinkerkit sensor Shield
2015-05-04T21:28:42.903
<p>I'm working with this <a href="http://knolleary.net/arduino-client-for-mqtt/" rel="nofollow">http://knolleary.net/arduino-client-for-mqtt/</a>. I'm using Arduino Uno + Ethernet shield + Tinkerkit Shield. But, if i have only Arduino Uno + Ethernet Shield, i can connect my arduino with MQTT and make publish/subscribe, but, when i put the tinkerkit shield, i lost the connection and i cannot connect any more. Any idea? Tinkerkit sensor shield is incompatible with mqtt? </p> <p>Thanks.</p>
<p>I think your problem is in wiring. Ethernet shield is using SPI communication, it requires pins: <code>SPI: 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK)</code>. Those pins must be left for the Ethernet shield. Information is from <a href="http://www.arduino.cc/en/Main/ArduinoBoardUno" rel="nofollow">Arduino Uno description</a>. </p> <p>Does your Arduino communicates with you after you plug-in Tinkerkit? If not, maybe you have a short in Tinkerkit shield. </p>
10552
|arduino-uno|lcd|
Program Arduino Uno as a digital clock
2015-05-04T22:58:35.400
<p>I have an arduino Uno board with a screen attached on top (<a href="http://www.freetronics.com.au/pages/16x2-lcd-shield-quickstart-guide#.VUf0tMWN0iT" rel="nofollow">http://www.freetronics.com.au/pages/16x2-lcd-shield-quickstart-guide#.VUf0tMWN0iT</a> This is the screen). </p> <p>I'm trying to get it so that the screen displays the time in hours, minutes and seconds and counts on a 24 hours loop. Like a digital clock. I have it so that it can count but it just counts up to 99 then repeats. </p> <p>I have this code which counts milliseconds but I need minutes and hours </p> <pre><code> #include &lt;Wire.h&gt; #include &lt;LiquidCrystal.h&gt; LiquidCrystal lcd(8, 9, 4, 5, 6, 7); void setup() { lcd.begin( 16, 2 ); } void loop() { lcd.setCursor ( 0, 1); lcd.print(millis()); } </code></pre>
<p>The takeaway from the previous answers is that your best option is to use an RTC (real-time clock). Failing that, you can emulate the RTC using <code>millis()</code>, at the cost of a significant drift, especially if your Arduino is clocked off a ceramic resonator.</p> <p>I would just like to add that you do not have to write the logic of that <code>millis()</code>-based “soft RTC” yourself, as this has already implemented in the <a href="https://adafruit.github.io/RTClib/html/class_r_t_c___millis.html" rel="nofollow noreferrer"><code>RTC_Millis</code> class</a> from <a href="https://github.com/adafruit/RTClib" rel="nofollow noreferrer">Adafruit's RTClib</a>:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;RTClib.h&gt; #include &lt;LiquidCrystal.h&gt; RTC_Millis rtc; LiquidCrystal lcd(8, 9, 4, 5, 6, 7); void setup() { rtc.begin(DateTime(F(__DATE__), F(__TIME__))); lcd.begin(16, 2); } void loop() { static DateTime last_time_printed; DateTime now = rtc.now(); if (now != last_time_printed) { lcd.setCursor(0, 1); lcd.print(now.timestamp(DateTime::TIMESTAMP_TIME)); last_time_printed = now; } } </code></pre> <p>One nice thing about this option is that, if you later opt for a real RTC, you will only need to do minimal changes to your code. Another nice thing is that, if you measure the drift of your clock, you can easily correct it: just replace <code>RTC_Millis</code> with <a href="https://adafruit.github.io/RTClib/html/class_r_t_c___micros.html" rel="nofollow noreferrer"><code>RTC_Micros</code></a> and call <code>rtc.adjustDrift()</code> in <code>setup()</code>. You will be able to adjust the drift with a 1&nbsp;<a href="https://en.wikipedia.org/wiki/Parts-per_notation" rel="nofollow noreferrer">ppm</a> resolution. Note that both <code>RTC_Millis</code> and <code>RTC_Micros</code> are immune to rollover problems.</p>
10556
|attiny|isp|
Programmed device causes issues between computer and ISP
2015-05-05T02:23:31.777
<p>I'm using a Digispark, which is basically an attiny85 packaged with a few other things, as an ISP to program attiny85's. The Digispark is loaded with Littlewire and recognized as an USBtinySPI device on the computer. The target attiny85 to be programmed is stacked on top of the Digispark. All pins are connected 1-to-1, 2-to-2, etc. Programming is done from the Arduino IDE. The tutorial I followed can be found here...</p> <p><a href="http://digistump.com/wiki/digispark/tutorials/programming" rel="nofollow">http://digistump.com/wiki/digispark/tutorials/programming</a></p> <p>The Digispark uses port 3 (USB-) and port 4 (USB+) to communicate with the computer. There are series resistors and shunt zener diodes on both USB connections. The Digispark schematic can be seen here...</p> <p><a href="https://s3.amazonaws.com/digispark/DigisparkSchematicFinal.pdf" rel="nofollow">https://s3.amazonaws.com/digispark/DigisparkSchematicFinal.pdf</a></p> <p>I have been happily programming attiny85's with this setup, but recently hit a snag. On the target chip, if port 3 or 4 produce an output, the computer will no longer recognize the programmer. The computer will immediately connect to the programmer once the target chip is removed from it's socket. The target chip must be messing up communication between the computer and the programmer. </p> <p>Curious if I was missing something, I compared my setup with Sparkfun's Tiny AVR Programmer. It seems like a more robust programmer. I thought it might have extra components or something, but it's almost identical. It uses an attiny84 with pins directly connected to an attiny85.</p> <p>After lots of random guesses, I added series 2.2kohm resistors on ports 3 and 4 between the target attiny85 and the programmer. This solves the problem, but seems like a workaround.</p> <p>Am I missing something? It seems like a programmer should be able to work without worrying about what the pins on the target device are doing. I assumed poorly, that was the purpose behind the RESET pin. Is there a better solution?</p>
<p>With the Tiny AVR programmer, the <code>D+</code> and <code>D-</code> lines are connected to there own input pins on the ATtiny84, see below:</p> <p><img src="https://i.stack.imgur.com/k3yKU.png" alt="enter image description here"></p> <p>This means that the pins from the target chip do not interfere with the function of these. </p> <p>Whereas the digistump board has the outputs of the USB connected to pin <code>3</code> and <code>4</code>, these pins are also connected to pin <code>3</code> and <code>4</code> of the target, as you know,</p> <p><img src="https://i.stack.imgur.com/yTs4d.png" alt="enter image description here"></p> <p>This means that as soon as you have your outputs active on <code>3</code> and <code>4</code> these interrupt the function of the USB lines.</p> <p>By adding the 2.2k you are increasing the resistance before the Zener regulator circuit(thus decreasing the effect of the voltage from the target on these lines) and allowing the main tiny to have 'control' over the bus lines. </p> <p>This is actual done on the <a href="http://www.kanda.com/avr-isp-circuits.html" rel="nofollow noreferrer">SPI buses</a> as well when a ISP is programming a target, while the target has other SPI chips on the bus, you add series resistors on the SPI bus, as seen below:</p> <p><img src="https://i.stack.imgur.com/4h12S.jpg" alt="enter image description here"></p> <p>The <strong>R</strong> is usually between 1k - 4k7ohm. So you method is not a workaround, but normal procedure.</p> <p>Another method to use instead of the resistor would be to cut the traces on the <strong><em>target board</em></strong> for pins <code>3</code> and <code>4</code>, thus preventing it from going back onto the USB line. This is as I see no need to have control over the USB lines from the target.</p> <blockquote> <p>Am I missing something? It seems like a programmer should be able to work without worrying about what the pins on the target device are doing. I assumed poorly, that was the purpose behind the RESET pin. Is there a better solution?</p> </blockquote> <p>The programmer only toggles reset when programming, and once the target is flashed with your firmware that uses the same lines as USB and the PC then does not recognize the programmer because of this, the programmer won't be able to issue a RESET to the target, as </p> <ol> <li>the PC can't issue it, </li> <li>the programmer won't know to do that on its own.</li> </ol>
10563
|serial|c++|arduino-nano|ir|
Arduino IR not returning data
2015-05-05T08:25:38.993
<p><strong>THIS QUESTION ISN'T IN USE ANYMORE</strong></p> <blockquote> <p>Solved by using an other remote that is supported by the libary</p> </blockquote> <p><strong>====NEW CODE====</strong></p> <pre><code> #include &lt;IRremote.h&gt; int RECV_PIN = 11; int relay1 = 2; int relay2 = 3; int relay3 = 4; int on = 1; int on1 = 1; int on2 = 1; IRrecv irrecv(RECV_PIN); decode_results results; void setup() { digitalWrite(relay3, HIGH); pinMode(relay3, OUTPUT); digitalWrite(relay2, HIGH); pinMode(relay2, OUTPUT); digitalWrite(relay1, HIGH); pinMode(relay1, OUTPUT); pinMode(13, OUTPUT); irrecv.blink13(true); irrecv.enableIRIn(); } unsigned long last = millis(); void loop() { if (irrecv.decode(&amp;results)){ if (results.value == 0x36167A85) { if (millis() - last &gt; 250) { on = !on; digitalWrite(relay1, on ? HIGH : LOW); } last = millis(); } else if (results.value == 0x36161AE5) { if (millis() - last &gt; 250) { on1 = !on1; digitalWrite(relay2, on1 ? HIGH : LOW); } last = millis(); } else if (results.value == 0x3616FA05) { if (millis() - last &gt; 250) { on2 = !on2; digitalWrite(relay3, on2 ? HIGH : LOW); } last = millis(); } irrecv.resume(); } } </code></pre> <p><strong>================</strong></p> <p>I'm working on this bit of arduino code for a while now but i can't get it to work. My circuit is wired up correctly, but it isn't returning any data in the serial prompt. Here is my code:</p> <pre><code>#include &lt;IRremote.h&gt; int RECV_PIN = 11; IRrecv irrecv(RECV_PIN); decode_results results; int main = 0; int left = 0; int right = 0; void setup() { Serial.begin(9600); irrecv.enableIRIn(); } void loop() { if (irrecv.decode(&amp;results)) { Serial.println(results.value, HEX); switch (results.value) { case 0x2E3A06C0: main = 1; Serial.println("MAIN: on"); break; case 0x8C2921D6: left = 1; Serial.println("LEFT: on"); break; case 0x226270DA: right = 1; Serial.println("RIGHT: on"); break; case 0x4AC6E6A: main = 0; Serial.println("MAIN: off"); break; case 0xDD5E26EF: left = 0; Serial.println("LEFT: off"); break; case 0x3E5BEF99: right = 0; Serial.println("RIGHT: off"); break; } irrecv.resume(); } delay(100); } </code></pre> <p>I'm using the libary Arduino-IRremote. When I try the demo "IRrecvDemo", it works fine. I have the hex codes from this demo. So can someone help me get this code working? It would be nice!</p>
<p><strong>THIS QUESTION ISN'T IN USE ANYMORE</strong></p> <blockquote> <p>Solved by using an other remote that is supported by the libary and tweaking the code.</p> </blockquote> <p><strong>====NEW CODE====</strong></p> <pre><code> #include &lt;IRremote.h&gt; int RECV_PIN = 11; int relay1 = 2; int relay2 = 3; int relay3 = 4; int on = 1; int on1 = 1; int on2 = 1; IRrecv irrecv(RECV_PIN); decode_results results; void setup() { digitalWrite(relay3, HIGH); pinMode(relay3, OUTPUT); digitalWrite(relay2, HIGH); pinMode(relay2, OUTPUT); digitalWrite(relay1, HIGH); pinMode(relay1, OUTPUT); pinMode(13, OUTPUT); irrecv.blink13(true); irrecv.enableIRIn(); } unsigned long last = millis(); void loop() { if (irrecv.decode(&amp;results)){ if (results.value == 0x36167A85) { if (millis() - last &gt; 250) { on = !on; digitalWrite(relay1, on ? HIGH : LOW); } last = millis(); } else if (results.value == 0x36161AE5) { if (millis() - last &gt; 250) { on1 = !on1; digitalWrite(relay2, on1 ? HIGH : LOW); } last = millis(); } else if (results.value == 0x3616FA05) { if (millis() - last &gt; 250) { on2 = !on2; digitalWrite(relay3, on2 ? HIGH : LOW); } last = millis(); } irrecv.resume(); } } </code></pre> <p><strong>================</strong></p>
10565
|serial|clones|arduino-uno-smd|
How do I use the additional serial ports on an Arduino UNO R3 clone?
2015-05-05T08:47:11.410
<p><img src="https://i.stack.imgur.com/AJKKC.jpg" alt="Clone"></p> <p>I bought <a href="http://www.ebay.com/itm/ATmega328P-CH340G-UNO-R3-Development-Board-Free-USB-Cable-for-Arduino-TGSNUYS-/261844126901?ssPageName=ADME:X:RRIRTB:US:3160" rel="nofollow noreferrer">this</a> Arduino clone over eBay. It seems to have an extra SPI and serial ports. How do I use these?</p>
<p>UNO means ATmega328. It has always only one serial and one I2C port regardless of how many connectors (or solder pads) it is hooked to. They are just parallel outputs to ATmega pins: <code> D0 - TX D1 - RX A5 - SCL A4 - SDA</code></p> <p>Extra pads are just for user convenience, for easier wiring. </p>
10571
|attiny|ir|isp|
IR not working on Attiny85
2015-05-05T11:02:57.997
<p>After countless attemps on making this thing work i'm not sure what the hell is going on. First of all you can't use the normal IR library because Attiny85 is crap and due to timer isses it wont work. So basicaly you need just the specific part which gets the data from the remote and thats all. This is what i did but i failed badly again.</p> <p>This time i used the simplest possible code which works perfectly on the Arduino UNO but it wont do anything on the Attiny85</p> <h2>The code</h2> <pre><code>int irPin = 4; int tipPin = 3; int start_bit = 2200; //Start bit threshold (Microseconds) int bin_1 = 1000; //Binary 1 threshold (Microseconds) int bin_0 = 400; //Binary 0 threshold (Microseconds) boolean state = 0x0; void setup() { pinMode(tipPin, OUTPUT); pinMode(irPin, INPUT); //Serial.begin(9600); //Serial.println(&quot;IR/Serial Initialized: &quot;); } void loop() { int key = getIRKey(); //Fetch the key //Serial.println(key); if (key != 0) { state != state; digitalWrite(tipPin, state); } delay(400); // avoid double key logging (adjustable) } int getIRKey() { int data[12]; int i; while(pulseIn(irPin, LOW) &lt; start_bit); //Wait for a start bit for(i = 0 ; i &lt; 11 ; i++) data[i] = pulseIn(irPin, LOW); //Start measuring bits, I only want low pulses for(i = 0 ; i &lt; 11 ; i++) //Parse them { if(data[i] &gt; bin_1) //is it a 1? data[i] = 1; else if(data[i] &gt; bin_0) //is it a 0? data[i] = 0; else return -1; //Flag the data as invalid; I don't know what it is! Return -1 on invalid data } int result = 0; for(i = 0 ; i &lt; 11 ; i++) //Convert data bits to integer if(data[i] == 1) result |= (1&lt;&lt;i); return result; //Return key number } </code></pre> <p>The ouput values are 3-digit numbers which work OK and i'm not even checking the value here. Just if something came in. And it doesn't bloody work!!!!</p> <h2>Stuff i've already checked</h2> <ul> <li>The circuit</li> <li>If the pin works</li> <li>If the timers are set correctly</li> <li>Using adafruits library</li> <li>Changing every possible core</li> <li>If the receiver works</li> <li>The wiring</li> </ul>
<p>If you are trying to toggle the LED when a signal comes in, then there is a glitch in the code and I have no idea how the UNO worked for you as I tried and it only spat out Serial, but didn't do anything with the LED.</p> <p>Try changing this line of code:</p> <p><code>state != state;</code></p> <p><strong>to</strong> </p> <p><code>state = !state</code></p> <p>you are not actually toggling the LED <code>state</code> with the other line, but instead doing a logical <code>not equal to</code> which won't do what you want.</p>
10575
|arduino-uno|c|isp|
Arduino/DuinOS vs Normal C/ARM Programming
2015-05-05T14:27:15.000
<p>I'm trying to understand the difference between programming Arduino hardware (Atel/ARM based) versus 'normal C-based ARM programming'.</p> <p>My <em>understanding</em> is that the Arduino language is cross-compiled into C-compatible binary, and the Arduino EEPROM libraries are used to effectively 'flash' your Arduino code onto the Atel/ARM chip, which is running DuinOS. Your Arduino 'app' (software) can then take advantage of DuinOS utilities, such as scheduling, semaphores, events, critical sections, etc.</p> <p>My <em>understanding</em> is that if I wanted to program an ARM chip myself from scratch, I would have to use something called an ISP programmer to 'flash' an embedded RTOS onto the chip first. Then, I would have to write C code, compile it, and again use the ISP programmer to deploy the compiled binary to the ARM chip, which is already setup to boot the RTOS when powered on.</p> <p>I'm sure I'm mucking up a few things here, but this is my general understanding: can someone correct/clarify these things for me?</p>
<blockquote> <p>My understanding is that the Arduino language is cross-compiled into C-compatible binary,</p> </blockquote> <p>There is no "Arduino language". Programs are written in C++ or C, and the IDE mangles them in certain ways in order to ease development by beginners (and on occasion frustrate development by veterans).</p> <blockquote> <p>and the Arduino EEPROM libraries are used to effectively 'flash' your Arduino code onto the Atel/ARM chip,</p> </blockquote> <p>No. The uploading of the compiled code is done using a separate program, usually <a href="http://www.nongnu.org/avrdude/" rel="nofollow noreferrer">AVRDUDE</a> or <a href="http://www.shumatech.com/web/products/bossa" rel="nofollow noreferrer">bossac</a>, and the code is uploaded into flash. Data can be optionally uploaded into EEPROM via the same program, but this is not required.</p> <blockquote> <p>which is running DuinOS. Your Arduino 'app' (software) can then take advantage of DuinOS utilities, such as scheduling, semaphores, events, critical sections, etc.</p> </blockquote> <p>Not by default. If you want to use DuinOS then you will need to download, compile, and upload it yourself.</p> <blockquote> <p>My understanding is that if I wanted to program an ARM chip myself from scratch, I would have to use something called an ISP programmer to 'flash' an embedded RTOS onto the chip first. Then, I would have to write C code, compile it, and again use the ISP programmer to deploy the compiled binary to the ARM chip, which is already setup to boot the RTOS when powered on.</p> </blockquote> <p><a href="https://electronics.stackexchange.com/questions/80933/do-i-need-an-os-in-my-device">Nope.</a> Any system can be run <a href="https://raspberrypi.stackexchange.com/questions/542/using-raspberry-pi-without-a-linux-os">without an OS</a>.</p>
10578
|arduino-ide|library|c|
Writing C Program outside of Arduino IDE?
2015-05-05T16:34:27.310
<p>I like the idea of using the Arduino IDE for simple projects and for getting started with Arduino, but the <em>consensus</em> I've gotten so far is that it is for those who are new to Arduino and/or programming in general.</p> <p>My <em>understanding</em> is that it is possible to write a C program from scratch, completely outside of the Arduino IDE, and then use a tool like AVRDUDE to upload it to an Arduino MCU. This option, albeit appealing and interesting, leaves me with a few concerns:</p> <ul> <li>What Arduino libraries would need to be imported/linked by such a "raw C" program? I assume that when an Arduino IDE-based program executes a <code>digitalWrite(...)</code> it is <em>really</em> calling a C lib, probably provided by Arduino, under the hood. I am concerned about making sure all these "underlying libs" get included with my C program. Thoughts?</li> <li>Is anything else "lost" by flying solo and venturing outside the Arduino IDE? Any capabilities/features that I would now have to "roll my own"?</li> </ul>
<p>Yes, you can write a program outside Arduino IDE. For example I tried Eclipse IDE with AVR plug-in and now I stick with AVR Studio. Of course,you won't have some functions that you maybe usually use when you write in Arduino IDE and also some libraries. But, why not to try implementing stuff. Why to limit yourself to functions and libraries made by others when you can learn and write your owns, maybe better than the existing ones. </p>
10581
|arduino-uno|sensors|analogread|analogwrite|
When and where do I have to worry about accounting for sensor "noise"?
2015-05-05T18:53:36.740
<p>I just watched this <a href="https://www.youtube.com/watch?v=_LCCGFSMOr4" rel="nofollow">excellent video tutorial</a> that shows a simple Arduino program that toggles an LED via a pushbutton. Very cool!</p> <p>Being brand new to electronics/robotics, I was shocked that something as simple as a pushbutton required his <code>debounce</code> behavior. That's something I would have never thought about in a million years. What is the 'rule of thumb' for when this type of <code>debounce</code> behavior (regardless of what sensor we're talking about, pushbutton or otherwise) must be accounted for? Is it simply that any type of <em>analog sensor</em> can generate this kind of unexpected 'noise'?</p> <p>Can someone provide other examples for when special code must be put in place to accommodate unexpected sensor noise?</p>
<p>Anyone who believes sensors do not have noise has never used one. True you may not encounter noise while reading the digital information, but I promise you the information will have noise in it. Noise from a switch can be dealt with by hardware or software, such as his debounce behavior. Other sensor noise is 4 years of study at college. Look into Kalman Filters, probabilistic robotics. Even the self driving cars you hear about currently require large compute capacity, mostly in order to deal with sensor noise.</p>
11586
|arduino-uno|system-design|prototype|
Arduino: Breadboards and PCBs
2015-05-06T00:10:43.870
<p>I just watched this <a href="https://www.youtube.com/watch?v=_LCCGFSMOr4" rel="nofollow">excellent video tutorial</a> that shows a simple Arduino program that toggles an LED via a pushbutton. Very cool!</p> <p>In the video, the author is using a breadboard for prototyping his circuit. What's the next "step up" from this? In other words, say I get my breadboard circuit working perfectly, is it now time to create a PCB? If my understanding of circuitry is correct, this is <em>not</em> a trivial process. I would need a CAD program to design my circuit, and it would likely be very expensive to get the design actually fabricated. At least too expensive for simple hobby purposes. <strong>Is there a middle ground between breadboard and PCB?</strong></p>
<blockquote> <p>Is there a middle ground between breadboard and PCB?</p> </blockquote> <p>A prototype PCB with breadboardlike layout is a fast way to turn a breadboard design into a permanent build. So it may be in the range of valid answers to your question.</p> <p>(-: <em>The link below is just an example, there are lots of other names, designs and sellers and I am in no way releated to any of those...</em> :-)</p> <p><a href="https://www.tindie.com/products/Schmart/400-tiepoint-schmartboard-breadproto-board-bundle/" rel="nofollow">https://www.tindie.com/products/Schmart/400-tiepoint-schmartboard-breadproto-board-bundle/</a></p>
11592
|arduino-uno|motor|servo|arduino-motor-shield|
Do I need the Motor Shield to drive servo motors?
2015-05-06T08:28:02.360
<p>I was perusing Arduino's list of official shields and noticed the <a href="http://www.arduino.cc/en/Main/ArduinoMotorShieldR3" rel="nofollow">Motor Shield</a> that can be used to drive up to 2 servo motors.</p> <p>Being brand new to Arduino/robotics, I am wondering: do I <em>really</em> need this shield to drive a set of servos?</p> <ul> <li>What does this shield really offer in the way of driving motors?</li> <li>What is lost by <em>not</em> using this shield?</li> <li>What if I my project has more than 2 motors?!?</li> </ul>
<p>You don't need this shield to drive <em>servo</em> motors, they have their own controller, you need just a 5V power line, GND and digital output pin to generate a PWM and that's it. Usually Arduino has enough power to drive <strong>servo motors</strong>. </p> <p>This shield you are talking about is used for DC (direct current) and stepper motor. These motors need power gain and the shield provides it and often has a chip called L298N (which implements <a href="http://en.m.wikipedia.org/wiki/H_bridge" rel="nofollow">H-bridge</a>) with MOSFETs to properly feed the motor.</p> <p><strong>What does this shield really offer in the way of driving motors?</strong></p> <p>A proper circuit and components so you plug your motor and connect into your board leaving you just the programming task to control motor's position and speed.</p> <p><strong>What is lost by not using this shield?</strong></p> <p>Actually, you use this kind of component just for practice purposes. It is already built and you just use it. However, it's a good learning process building the H-bridge yourself and understanding how it works and why it is necessary (if you have time, this is a good task).</p> <p><strong>What if I my project has more than 2 motors?!?</strong></p> <p>Well, just decide how many H-bridges you need. This shield has the capacity for 2 DC motors or 1 stepper motor. In case they are servo motor, you just use this <a href="http://www.arduino.cc/en/Reference/Servo" rel="nofollow">lib</a>. It is possible to have plenty of servos working together and all you need are good battery and enough digital pins. They share timers of microcontroller, that's why it works for many motors.</p>
11594
|motor|arduino-due|electronics|solar|
How to tell what components are compatible with Arduino Due?
2015-05-06T08:49:04.413
<p>I am interested in using the <a href="http://www.arduino.cc/en/Main/ArduinoBoardDue" rel="nofollow">Arduino Due</a> in an upcoming project, however I am worried that the other shields/components that I need will not be compatible with it, because, according to that link:</p> <blockquote> <p>The Due is compatible with all Arduino shields that work at 3.3V and are compliant with the 1.0 Arduino pinout.</p> </blockquote> <p>The components I need to use are:</p> <ul> <li>NightShade Electronics <a href="http://www.ns-electric.com/products/energyshield/" rel="nofollow">energyShield</a></li> <li><a href="http://www.adafruit.com/products/200" rel="nofollow">Solar Panel</a></li> <li><a href="http://www.adafruit.com/products/1143?gclid=CjwKEAjw96aqBRDNhM6MtJfE-wYSJADiMfgguI7rTduiPEzHwVkcWxKifp1IMtwpI6VHO8btHORRKBoCStHw_wcB" rel="nofollow">Servo Motors</a></li> </ul> <p>Essentially a solar panel will power the energyShield (rechargeable battery), which in turn will power multiple servo motors.</p> <p>I cannot tell if the energyShield uses the 1.0 pinout or not. I am also worried that since the the solar power generates 6V it will overload the energyShield which is rated at 3.3V. At the same time, I am worried that the servo motors, which seem to require 4.8V, will not be capable of being powered by the energyShield which outputs 3.3V. Thoughts?</p> <p>Bonus Points if someone can explain to me what the "1.0 Pinout" is, and whether it is the latest/most modern pinout available for Arduinos.</p>
<p>As far as I understood this energyShiled accepts any input between 5-24V and output 5 - 3.3V. This specs are compatible with arduino Due. And with the solar panel.</p> <p>You can always power servos from seperate source or from the same battery but with seperate direct line.</p>
11599
|arduino-ide|avrdude|
how can I change the setting for number of upload retries in the IDE?
2015-05-06T14:20:03.077
<p>I run into this problem when I mess something up, and it's pretty annoying to wait for 10 not in sync timeouts before I can try some different method.</p> <pre><code>... avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x85 </code></pre> <p>How can I set the number of "attempts" to say 2 instead of 10? Or how can I safely interrupt the upload process in the IDE?</p>
<p>The code is not in the arduino ide but in the tool chain (.exe) that it runs. </p> <p>Normally it is a program called avrdude.exe that is running so you would need to rebuild the avrdude.exe tool which is not practical.</p> <p>The easiest way, but rather crude, is to pull the usb cable. If the port disappears avrdude should stop immediately.</p>
11601
|arduino-ide|
How to see log from Arduino IDE?
2015-05-06T16:14:50.090
<p>Where can I see outputs from such instruction in an ino file ?</p> <pre><code>Serial.println("my message"); </code></pre>
<p>Call <code>Serial.begin(9600)</code> in your <code>setup()</code> function:</p> <pre><code>void setup() { Serial.begin(9600); } </code></pre> <p>Call <code>Serial.print('example')</code> or <code>Serial.println('example')</code> in your <code>loop()</code> function (or one of your own functions that your <code>loop()</code> function calls:</p> <pre><code>void loop() { Serial.print('example'); Serial.print('example'); // Output of the two calls above: exampleexample Serial.println('example'); Serial.println('example'); // Output of the two calls above: // example // example } </code></pre> <p>Go to <strong>Tools</strong> &gt; <strong>Serial Monitor</strong> to see the output.</p> <p>References:</p> <ul> <li><a href="https://www.arduino.cc/reference/en/language/functions/communication/serial/print/" rel="nofollow noreferrer">https://www.arduino.cc/reference/en/language/functions/communication/serial/print/</a></li> <li><a href="https://www.arduino.cc/reference/en/language/functions/communication/serial/println/" rel="nofollow noreferrer">https://www.arduino.cc/reference/en/language/functions/communication/serial/println/</a></li> </ul>
11602
|arduino-nano|ftdi|
what ftdi windows driver for arduino nano
2015-05-06T16:16:42.673
<p>at <a href="http://www.ftdichip.com/FTDrivers.htm" rel="nofollow">http://www.ftdichip.com/FTDrivers.htm</a> they seem to divide chips into two categories, FT4222H vs. D2XX driver. </p> <p>What's the correct for a arduino nano?</p>
<p>The <a href="http://www.arduino.cc/en/Main/arduinoBoardNano" rel="nofollow">Official Arduino Nano</a> has an FTDI FT232RL.</p> <p>You want to use the <a href="http://www.ftdichip.com/Drivers/VCP.htm" rel="nofollow">Virtual Com Port(VCP) Driver</a> so the FTDI device appears as a COM port under windows.</p> <p>See the <a href="http://www.arduino.cc/en/Guide/Windows#toc4" rel="nofollow">getting started guide</a> for details.</p>
11610
|arduino-uno|battery|solar|
Implementing Quasi-Perpetual Battery on Arduino
2015-05-06T18:19:13.410
<p>I am interested in seeing how much "<em>uptime</em>" I can achieve with my Arduino device/project. I am brand new to electronics/robotics, and so I wanted to bounce my idea off of this community first and see if I am overlooking anything obvious/major, or if my overall approach is incorrect.</p> <p>The idea is simple:</p> <p>Provide my Arduino device with 2+ "rechargeable power sources" (described next) and then provide a mechanism to route power to any viable (non-dead) power source at any time. While one power source is being used to power the Arduino device, the other "idling" power sources are recharging. The intention is to allow the device to keep switching between power sources endlessly, in perpetuity, achieving 100% uptime (perfect "high availability").</p> <p>As for each "rechargeable power source" I am thinking an <a href="http://www.ns-electric.com/products/energyshield/" rel="nofollow">energyShield</a> (rechargeable Li-polymer) backed by a <a href="http://www.adafruit.com/products/200" rel="nofollow">solar panel</a>.</p> <p>I did some preliminary research and was told that if I were to wire these power sources in series with diodes, then the circuit would always by default draw power from the source with the highest voltage. As soon as another source has higher voltage, the circuit begins drawing power from that one, and the "old source" begins recharging.</p> <p>I'm a noob but not a fool, and I <strong>know</strong> there is no such thing as perpetual energy (hence the title "quasi-perpetual"), and I'm sure factors like sunlight/weather conditions/etc. would affect the efficacy of the solar panels, etc. But I guess my first concern is: am I doin' it right? Are there any caveats/pitfalls or considerations I'm overlooking here?</p> <p>Assuming I'm more or less correct in my approach, the other concern is how to actually implement power sources and diodes in a series, and how to actually rig that all up and connect it to the Arduino board. Again, I'm a total electronics newbie, so I'm just having a tough time visualizing the precise solution there.</p> <p>And as for determining the <em>actual</em> number of power sources (energyShield + solar panel combo) my device would need, I was just planning on starting with 2, and running the device at max power and monitoring their recharge rates. The more sources I add, the longer the device will operate. Obviously, at some point I'll either reach a point where its uptime is sufficient for my needs, or I'll run out of money. :-)</p>
<p>"I did some preliminary research and was told that if I were to wire these power sources in series with diodes, then the circuit would always by default draw power from the source with the highest voltage."</p> <p>That is not correct - you need the two sources in parallel with a diode each. Then the higher voltage will become the current source. When the sources are charging, the charge source may become the current source if that voltage is higher than the other stored charge source.</p>
11624
|arduino-uno|interrupt|adafruit|
Adafruit CC3000 Wifi Shield on IRQ 2?
2015-05-07T09:00:01.230
<p>I'm using an AdaFruit CC3000 Wifi shield as an HTTP server with an Arduino Uno. </p> <p>I have a script which works fine -- logs into my Wifi and listens for connections as it should. </p> <p>However, I want to use an infrared library which writes to the CC33000 default IRQ 3, so to avoid conflict I change the following setting:</p> <pre><code>#define ADAFRUIT_CC3000_IRQ 3 // MUST be an interrupt pin! </code></pre> <p>to the only other Interrupt pin</p> <pre><code>#define ADAFRUIT_CC3000_IRQ 2 // MUST be an interrupt pin! </code></pre> <p>The device hangs at "Initializing" .. or at least I see neither of the subsequent lines in the following code on my serial monitor:</p> <pre><code>Serial.println(F("\nInitializing...")); if (!cc3000.begin()) { Serial.println(F("Couldn't begin()! Check your wiring?")); while(1); } Serial.print(F("\nAttempting to connect to ")); Serial.println(WLAN_SSID); if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) { Serial.println(F("Failed!")); while(1); } </code></pre> <p>I've stripped everything back down to just the example code for HTTPServer to ensure it's not a conflict with my own code or the IR Library. I've changed the setting from 2 to 0 and 1 thinking there was some confusion over literal IRQs vs Pins, but those settings generate the "Couldn't begin" error trap. </p> <p>Is there any other setting that I need to vary in order to get the CC3000 to opearate on IRQ 2 or is this a hardware bug and I'm out of luck if I want to use Pin 3?</p>
<p>It is a "hardware bug" as you so aptly put it. As far as I know, the only way to get the CC3000 board to use pin 2 as the IRQ is to physically rewire the connections. I did exactly that on my board and it works without a problem, leaving pin 3 free to use for whatever else you want. You can see what I did <a href="https://arduino.stackexchange.com/questions/9740/arduino-motor-shield-and-adafruit-cc3000-wifi-shield-compatibility"><strong>here</strong></a>. It basically involves cutting the trace wire and running a jumper cable between the holes next to the pins.</p> <p>The important thing to understand perhaps is that pins 2 and 3 are available to use for IRQ on the Mega and Uno, but it is an actual dedicated pin on the CC3000, hence why you have to go to this effort to change it. Also remember that once you have cut the trace to pin 3 it becomes an open/free pin and is no longer connected to the wifi shield. By the sounds of your requirements this shouldn't matter, but it is still useful to know.</p> <p>If you haven't already, I recommend that you read the <a href="https://learn.adafruit.com/downloads/pdf/adafruit-cc3000-wifi.pdf" rel="nofollow noreferrer">documentation for the CC3000 board</a>, as it really helped me understand the irritating intricacies.</p> <p>But yeah, if you choose to follow this and reroute the pin, it works perfectly. Hope this helps, even if it is a bit late.</p>
11629
|arduino-uno|led|shields|ethernet|threads|
Multithreading Leds and Joystick
2015-05-07T11:33:21.350
<p>I'm trying to made a program that turn on and turn off leds with an input and send the coordinates of joystick, but, in the loop, the arduino makes one at a time, and i want make this in the same time. How can i make that? </p>
<blockquote> <p>the loop is something like this: </p> <pre><code>loop() { controlleds(); joystickevent(); } </code></pre> <p>but he runs, controlleds first, and joystickevent next, i want at the same time.</p> </blockquote> <p>There are typically two ways to read a simple potentiometer joystick: Connect it in a voltage divider and measure the analog voltage; and connect it in an R-C circuit and measure the time for the capacitor to charge.</p> <p>The first way is faster and you should not be able to notice the time difference between controlling the LEDs and reading the joystick.</p> <p>The second way takes longer and you might be able to notice. If this is how your joystick controller works, you would need to separately start the joystick reading, continue to poll the buttons control the LEDs, and check whether the joystick reading is ready yet. The joystick routine must not delay, waiting for the measurement to finish.</p>
11634
|programming|
Arduino: Put Data in Other File
2015-05-07T18:08:45.940
<p>The below code starts off with lots of data in the beginning, distracting the reader from the actual code. What is the best practice to clean this up:</p> <pre><code>#include &lt;Wire.h&gt; // For LED Backpack #include "Adafruit_LEDBackpack.h" #include "Adafruit_GFX.h" // For LCD Shield #include &lt;Adafruit_MCP23017.h&gt; #include &lt;Adafruit_RGBLCDShield.h&gt; // For pixel Units, such as hero #include &lt;Unit.h&gt; Adafruit_BicolorMatrix matrix = Adafruit_BicolorMatrix(); Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield(); Unit *hero; boolean doesNeedRedraw = true; boolean textNeedsRedraw = true; int8_t lastButtonPress = 0; int8_t frame = 0; void setup() { /* Important Setup Routine */ } static const uint8_t PROGMEM smile_bmp[] = { B00111100, B01000010, B10100101, B10000001, B10100101, B10011001, B01000010, B00111100 }, neutral_bmp[] = { B00111100, B01000010, B10100101, B10000001, B10111101, B10000001, B01000010, B00111100 }, frown_bmp[] = { B00111100, B01000010, B10100101, B10000001, B10011001, B10100101, B01000010, B00111100 }, walls_bmp[] = { B10100000, B10110000, B10010000, B11011100, B01000100, B01110100, B00010100, B00011100 }; void loop() { /* Important Main Loop Routine */ } </code></pre>
<p>There is actually not a lot wrong with the way the code is. You are writing / using embedded code. It is not expected to be some planned out UML model, and does not need to look like it is.</p> <p>If you just want less lines, start by converting your binary data to hex. Otherwise the answer of a global.h is valid (and I would still convert binary to hex). You could easily shrink 24 lines down to 3.</p> <p>If you could use a real IDE navigation would be unimportant, but since Arduino chose not to use a standard build process it takes extra effort (but still worth it). You could also switch to native AVR (and easily use a real IDE), which is what I plan to do as soon as the proof of concept is finished.</p>
11639
|arduino-uno|time|
Set start time for arduino uno clock
2015-05-07T22:01:08.697
<p>I'm programming an arduino uno with attached screen to be a clock and have the code below. It counts up from zero the milliseconds, seconds, minutes and hours and when it hits 24 hours it starts again from zero. Does anyone know how I can set the start time that it automatically starts at when it is reset? It will be a one off thing and I don't want it to interfere with the clock resetting to 0 hours after it hits 24. Thanks</p> <pre><code>#include &lt;Wire.h&gt; #include &lt;LiquidCrystal.h&gt; #define MILLIS_OVERFLOW 34359738 /** * Clock Variables */ unsigned long currentMillis, previousMillis, elapsedMillis; int seconds, minutes, hours; LiquidCrystal lcd(8, 9, 4, 5, 6, 7); void setup() { lcd.begin( 16, 2 ); } void loop() { setClock(); /** * After set clock now you have 3 int variables with the current time */ //seconds //minutes //hours lcd.setCursor ( 0, 1); lcd.print(hours); lcd.print(":"); lcd.print(minutes); lcd.print(":"); lcd.print(seconds); lcd.print(":"); lcd.print(elapsedMillis); } void setClock() { currentMillis = millis(); /** * The only moment when currentMillis will be smaller than previousMillis * will be when millis() oveflows */ if (currentMillis &lt; previousMillis){ elapsedMillis += MILLIS_OVERFLOW - previousMillis + currentMillis; } else { elapsedMillis += currentMillis - previousMillis; } /** * If we use equals 1000 its possible that because of the mentioned loop limitation * you check the difference when its value is (999) and on the next loop its value is (1001) */ if (elapsedMillis &gt; 999){ seconds++; elapsedMillis = elapsedMillis - 1000; } if (seconds == 60){ minutes++; seconds = 0; } if (minutes == 60){ hours++; minutes = 0; } if (hours == 24){ hours = 0; } previousMillis = currentMillis; } </code></pre>
<p>Assume you want the clock to start at 08:42:21, change</p> <pre><code>int seconds, minutes, hours; </code></pre> <p>to </p> <pre><code>int seconds = 21, minutes = 42, hours = 8; </code></pre> <p>Note that you should always also initialize (as in the second case above), and not only declare (as in the first case) all variables before you first read their values. Otherwise, for local variables you <a href="https://stackoverflow.com/a/11233616/143931">cannot be sure</a> what their initial value is. (Global variables are <a href="https://stackoverflow.com/q/14049777/143931">implicitly initialized</a> to zero if not explicitly initialized.)</p>
11640
|motor|
Arduino Stepper Motor Standing Desk help!
2015-05-07T23:10:58.447
<p>I currently have a standing desk at work, and I thought a fun way to learn Arduino would be to automate it, as it currently uses a hand crank.</p> <p>I would love some help determining what I would need for this task.</p> <p>What kind of motor should I use? -Stepper motor? -High/low rpm? -High/low torque? </p> <p>What sort of power would I need? </p> <p>Looking forward to hearing people's suggestions! </p>
<p>For initial playing, and possibly for a final solution, battery powered electric drills with external powering are an excellent source of reasonable wattage well geared down motors. Drills are often discarded when the batteries die and may be available free or at lo cost. </p> <p>For relatively low duty cycle use 9V drills operate OK on a small 12V battery and drills rated at up to 18V usually operate well enough on 12V. </p> <p>Use of a 12V lead acid battery charged by a trickle charger makes high current peaks easy to accommodate. Almot any condition battery will do - one which is too dead for eg motorcyle use probably works well enough here. Floating 12V lead acid batteries at 13.7 V allows them to be permanenetly connected to the "charger". A power pack can be used without a battery if enough current is provided. </p> <p>Battery powered drills typically have a two stage epicyclic gearbox giving typically hundreds of RPM output speed. If desired you can use the supplied switching which has a DPDT mechanical reversing switch. If you remove the mechanical reversing switch you can feed voltage directly to the motor. Changing polarity changes direction. </p> <p>Dismantling the gearbox can be educational but may be a one way journey. Beware a flood of ball bearings. </p>
11646
|arduino-mega|motor|relay|solar|
Relay feedback control
2015-05-08T08:58:56.433
<p>I have a two-relay system set up to a DC motor. So, if I close one relay, the motor moves on one way and if I close the second relay (and open the first) the motor goes on the other direction.</p> <p>I compare two variables (target inclination and real inclination) if they are not the same I would like to open one of the two relays UNTIL the are the same value. </p> <p>Both variables are calculated based on inclinometer input and some aritmethics.</p> <p>I do know how to calculate the variables, how to close the relay based in the comparation of variables and which relay open. </p> <p>But I don´t know how I can tell to open the relay because the motor has reached target inclination. </p> <p>How I can recalculate and compare constantly target inclination and real inclination when the relay is closed and the motor moving? Is this posible on Arduino? Is this multithreading?</p> <p>Thank you very much, any ideas are welcome!</p>
<p>Answering my own question, I think I found some way to get the solar panel face the sun.</p> <p>As said before, the inclinometer reads the position and makes some calculations using lookposition() function, then this happens:</p> <pre><code>void lookforsun() { while ((targetElevation + 3) &lt; realElevation | (targetElevation - 3) &gt; realElevation) { Serial.println("Elevation is not correct"); while (realElevation &lt; targetElevation) { Serial.println("Moving to south"); digitalWrite(south, LOW); lookposition(); } digitalWrite(south, HIGH); while (realElevation &gt; targetElevation) { Serial.println("Moving to north"); digitalWrite(north, LOW); lookposition(); } digitalWrite(north, HIGH); } while ((targetHourangle+3) &lt; realHourangle | (targetHourangle-3) &gt; realHourangle ) { Serial.print("Hour angle is not correct"); while (realHourangle &gt; targetHourangle) { Serial.println("Moving to east"); digitalWrite(east, LOW); lookposition(); } digitalWrite(east, HIGH); while (realHourangle &lt; targetHourangle) { Serial.println("Moving to west"); digitalWrite(west, LOW); lookposition(); } digitalWrite(west, HIGH); } </code></pre> <p>As you can see I took the frightening way of nested while loops, but appears to work.</p> <p>The first while measures if realElevation is between +-3 degrees of targetElevation, if realElevation is far away (target+-3) enters the second while loop, which determines if needs to go up or down.</p> <p>I included the +-3 because the sensor is so very sensible.</p> <p>Thank you very much Russell McMahon and portforwardpodcast for your ideas!</p>
11649
|arduino-uno|c|pointer|
cannot convert error with pointers
2015-05-08T10:30:28.203
<p>I write a code to store patterns for LED blinking, but I got this error:</p> <pre><code>led_basics:39: error: cannot convert 'char (*)[17][2]' to 'char*' in initialization led_basics:39: error: cannot convert 'char (*)[16][2]' to 'char*' in initialization led_basics:39: error: cannot convert 'char (*)[13][2]' to 'char*' in initialization </code></pre> <p>and so on for all pattern. How can I fix it? Here is the code:</p> <pre><code>char nulla[17][2]={{0,127},{8,125},{9,121},{10,113},{12,97},{14,65},{24,67},{27,71},{28,70},{30,78},{32,76},{36,88},{40,80},{42,112},{48,96},{56,64},{68,0}}; char egy[16][2]={{0,0},{9,4},{16,6},{18,2},{21,3},{27,7},{28,6},{30,14},{32,12},{36,24},{40,16},{42,48},{48,32},{51,96},{56,64},{68,0}}; char ketto[13][2]={{0,98},{7,99},{8,97},{12,113},{14,81},{20,89},{21,88},{24,74},{27,78},{30,70},{32,68},{36,64},{68,0}}; char harom[17][2]={{0,34},{7,35},{8,33},{10,41},{14,9},{17,73},{21,72},{24,74},{27,78},{30,70},{32,68},{36,80},{42,112},{48,96},{51,32},{56,0},{68,0}}; char negy[17][2]={{0,7},{7,6},{8,4},{9,0},{10,8},{21,9},{24,11},{27,15},{28,14},{32,12},{36,24},{40,16},{42,48},{48,32},{51,96},{56,64},{68,0}}; char ot[14][2]={{0,39},{8,37},{9,33},{10,41},{14,9},{17,73},{28,72},{30,64},{36,80},{42,112},{48,96},{51,32},{56,0},{68,0}}; char hat[17][2]={{0,62},{7,63},{8,61},{9,57},{12,41},{14,9},{17,73},{21,72},{24,74},{30,66},{32,64},{36,80},{42,112},{48,96},{51,32},{56,0},{68,0}}; char het[15][2]={{0,7},{8,5},{9,1},{24,3},{27,7},{28,6},{30,14},{32,12},{36,24},{40,16},{42,48},{48,32},{51,96},{56,64},{68,0}}; char nyolc[15][2] = {{0,127},{8,125},{9,121},{12,105},{14,73},{24,75},{27,79},{28,78},{32,76},{36,88},{40,80},{42,112},{48,96},{56,64},{68,0}}; char kilenc[13][2] = {{0,79},{8,77},{9,73},{24,75},{27,79},{28,78},{32,76},{36,88},{40,80},{42,112},{48,96},{56,64},{68,0}}; char kettospont[6][2] = {{0,0},{9,4},{12,20},{18,16},{24,0},{68,0}}; char *karakterek[11]={&amp;nulla,&amp;egy,&amp;ketto,&amp;harom,&amp;negy,&amp;ot,&amp;hat,&amp;het,&amp;nyolc,&amp;kilenc,&amp;kettospont}; </code></pre>
<p>As the second dimension is always 2, you can do this:</p> <pre><code>typedef char Tuple[2]; Tuple nulla[17] = {{0,127},{8,125},{9,121},{10,113},{12,97},{14,65},{24,67},{27,71},{28,70},{30,78},{32,76},{36,88},{40,80},{42,112},{48,96},{56,64},{68,0}}; Tuple egy[16] = {{0,0},{9,4},{16,6},{18,2},{21,3},{27,7},{28,6},{30,14},{32,12},{36,24},{40,16},{42,48},{48,32},{51,96},{56,64},{68,0}}; Tuple ketto[13] = {{0,98},{7,99},{8,97},{12,113},{14,81},{20,89},{21,88},{24,74},{27,78},{30,70},{32,68},{36,64},{68,0}}; // etc. Tuple* karakterek[3] = {nulla, egy, ketto}; // etc. </code></pre> <p>(The <code>typedef</code> makes it easier.)</p>
11657
|arduino-nano|
How does this Motor Circuit not ruin the Microcontroller
2015-05-08T15:46:43.973
<p>I came across this <a href="http://www.instructables.com/id/Simple-2-way-motor-control-for-the-arduino/" rel="noreferrer">instructable</a> about using no external hardware but two pwm pins to control a motor in both directions. Usually you would use an H bridge. However, ever since I have had my Arduino I have heard that you are not supposed to connect a pin to another pin. So how does this circuit works. It looks like he sends a signal from one pin and in my experience it would fry the board. So basically, my question is this circuit ok with an Arduino Nano and if so how does it work? Below is a picture of the setup he gave: <img src="https://i.stack.imgur.com/KPyz3.jpg" alt="enter image description here"></p>
<p>Another problem here is when running a motor you want to include a 'flyback diode' to prevent damage from voltage spikes, which is a problem with loads like motors.</p> <p>See <a href="http://www.nerdkits.com/videos/motors_and_microcontrollers_101/" rel="nofollow">this article</a> for details.</p>
11664
|serial|communication|terminal|
Sending data from txt file over serial connection
2015-05-08T20:28:49.880
<p>I'm trying to send data saved on a txt file to arduino over serial connection. I wrote this simple sketch</p> <pre><code>void setup(){ Serial.begin(9600); } void loop(){ while (Serial.available() &gt; 0) { Serial.write(Serial.read()); } } </code></pre> <p>When I try to send serial data from bash by typing <code>cat input.txt &gt;&gt; /dev/cu.wchusbserial1a1340</code> while the Arduino's serial connection window is open. It gives an error message "resource busy: /dev/cu.wchusbserial1a1340". Then I tried <code>cat input.txt &gt;&gt; /dev/tty.wchusbserial1a1340</code>. Now it hangs. Bash is busy, and it is not possible close Arduino IDE or serial connection window. What is wrong here?</p>
<p>As noted by jwpat7 the port can be accessed by one application at a time, so when the serial monitor is open no other application can access it. </p> <p>The hang might happen because when first connecting to an arduino port the arduino gets reset and waits for a second or so for programming data (that's how a new sketch is updated). I don't know for sure, but this might mess up with <code>cat</code> and make it to hang up.</p> <p>Best option might be to make a script like jwpat7's that would wait a second after opening the port and then send the file contents in.</p>
11674
|attiny|frequency|fuses|
Program ATtiny13 - 20PU
2015-05-09T08:32:52.753
<p>I'm trying to program my ATtiny 13 - 20PU. An it seems to work, but there is no action upon the "delay" command. If on the sketch below I comment out the "High" line, my led is off all the time and whenever I have a <code>Pin 4 High</code>, it's on all the time! Basically this seems to be a frequency/fuse/bootloader problem and made me think the upload was broken.</p> <p>I added a led between the tiny's pin 3 (digital pin 4) and ground with a 1k current limiting resistor. This one is for testing with the attached sketch. I also tried <a href="http://highlowtech.org/?p=1706" rel="nofollow">this breadboard circuit</a>, which gives exactly the same results.</p> <p>Upon upload to the tiny I get this:</p> <pre><code>Sketch uses 380 bytes (37%) of program storage space. Maximum is 1,024 bytes. Global variables use 8 bytes of dynamic memory. </code></pre> <p>(Everybody warns about 2 errors occuring upon a proper upload - I don't get those).</p> <p>My boards.txt look like this:</p> <pre><code>menu.cpu=Processor menu.clock=Clock attiny.name=ATtiny attiny.bootloader.tool=arduino:avrdude attiny.bootloader.unlock_bits=0xff attiny.bootloader.lock_bits=0xff attiny.build.core=arduino:arduino attiny.build.board=attiny attiny.upload.tool=arduino:avrdude attiny.menu.cpu.attiny45=ATtiny45 attiny.menu.cpu.attiny45.upload.maximum_size=4096 attiny.menu.cpu.attiny45.build.mcu=attiny45 attiny.menu.cpu.attiny45.build.variant=tiny8 attiny.menu.cpu.attiny85=ATtiny85 attiny.menu.cpu.attiny85.upload.maximum_size=8192 attiny.menu.cpu.attiny85.build.mcu=attiny85 attiny.menu.cpu.attiny85.build.variant=tiny8 attiny.menu.cpu.attiny44=ATtiny44 attiny.menu.cpu.attiny44.upload.maximum_size=4096 attiny.menu.cpu.attiny44.build.mcu=attiny44 attiny.menu.cpu.attiny44.build.variant=tiny14 attiny.menu.cpu.attiny84=ATtiny84 attiny.menu.cpu.attiny84.upload.maximum_size=8192 attiny.menu.cpu.attiny84.build.mcu=attiny84 attiny.menu.cpu.attiny84.build.variant=tiny14 attiny.menu.clock.internal1=1 MHz (internal) attiny.menu.clock.internal1.bootloader.low_fuses=0x62 attiny.menu.clock.internal1.bootloader.high_fuses=0xdf attiny.menu.clock.internal1.bootloader.extended_fuses=0xff attiny.menu.clock.internal1.build.f_cpu=1000000L attiny.menu.clock.internal8=8 MHz (internal) attiny.menu.clock.internal8.bootloader.low_fuses=0xe2 attiny.menu.clock.internal8.bootloader.high_fuses=0xdf attiny.menu.clock.internal8.bootloader.extended_fuses=0xff attiny.menu.clock.internal8.build.f_cpu=8000000L attiny.menu.clock.external8=8 MHz (external) attiny.menu.clock.external8.bootloader.low_fuses=0xfe attiny.menu.clock.external8.bootloader.high_fuses=0xdf attiny.menu.clock.external8.bootloader.extended_fuses=0xff attiny.menu.clock.external8.build.f_cpu=8000000L attiny.menu.clock.external16=16 MHz (external) attiny.menu.clock.external16.bootloader.low_fuses=0xfe attiny.menu.clock.external16.bootloader.high_fuses=0xdf attiny.menu.clock.external16.bootloader.extended_fuses=0xff attiny.menu.clock.external16.build.f_cpu=16000000L attiny.menu.clock.external20=20 MHz (external) attiny.menu.clock.external20.bootloader.low_fuses=0xfe attiny.menu.clock.external20.bootloader.high_fuses=0xdf attiny.menu.clock.external20.bootloader.extended_fuses=0xff attiny.menu.clock.external20.build.f_cpu=20000000L ################################################# attiny.menu.cpu.attiny13=ATtiny13 attiny.menu.cpu.attiny13.upload.maximum_size=1024 attiny.menu.cpu.attiny13.build.mcu=attiny13 attiny.menu.cpu.attiny13.build.variant=core13 attiny.menu.clock.internal96=9.6MHz (internal) attiny.menu.clock.internal96.bootloader.low_fuses=0x7A attiny.menu.clock.internal96.bootloader.high_fuses=0xff attiny.menu.clock.internal96.build.f_cpu=9600000L ################################################ attiny.menu.clock.internal48=4.8MHz (internal) attiny.menu.clock.internal48.bootloader.low_fuses=0x79 attiny.menu.clock.internal48.bootloader.high_fuses=0xff attiny.menu.clock.internal48.build.f_cpu=4800000L ################################################ </code></pre> <p>And I choose the settings: Board ATtiny, Processor ATtiny13, Clock 9.6 MHz (internal), Port Arduino Uno (same as when I upload the ISP sketch), Programmer Arduino as ISP. I upload by clicking "Upload using Programmer".</p> <p>Arduino Software is 1.6.4, the programmer Arduino is an Uno SMD edition. I used this <a href="https://arduinodiy.wordpress.com/2015/03/31/1256/#comment-907" rel="nofollow">programmer</a> and this <a href="https://arduinodiy.wordpress.com/2015/04/26/installing-attiny13-core-files-in-arduino-ide-1-6-x-and-1-7-x/" rel="nofollow">tutorial</a> for smeezkitty core13. </p> <p>I'm trying to upload this sketch:</p> <pre><code>// Blink sketch to test ATtiny Chips // ATMEL ATTINY13 / ARDUINO // // +-\/-+ // ADC0 (D 5) PB5 1|* |8 Vcc // ADC3 (D 3) PB3 2| |7 PB2 (D 2) ADC1 // ADC2 (D 4) PB4 3| |6 PB1 (D 1) PWM1 // GND 4| |5 PB0 (D 0) PWM0 // +----+ const int LED_PIN = 4; // digital pin const int DELAY_TIME = 1000; // time between blinks [ms] void setup() { pinMode(LED_PIN, OUTPUT); } void loop() { digitalWrite(LED_PIN, LOW); delay(DELAY_TIME); digitalWrite(LED_PIN, HIGH); delay(DELAY_TIME); } </code></pre> <p>Trying to burn a bootloader with the same settings as uploading to the tiny and then tools -> burn bootloader, get's me the error: </p> <pre><code>"efuse" memory type not defined for part "ATtiny13" Error while burning bootloader. </code></pre> <p>Skimming through the data sheet I noticed that the tiny13 - 20PU (the 20) stand for 20 MHz,... theoretically one should be able to downclock them to the ordinary 10 MHz, but maybe this is my problem?</p>
<p>The "efuse error" on burning the bootloader is described in the article you refer to and a solution is given there as well. It occurs when the attiny13 is defined in the same group as the attiny25/45/85 as the former has no efuse and the latter do.</p> <p>Giving the attiny13 its own menu entry in the IDE -as described in that article- should solve that.</p>
11676
|arduino-uno|memory-usage|
How to increase Arduino's memory to save Dot Matrix Library?
2015-05-09T08:50:06.053
<p>I need to display some dynamic Chinese characters to 12864 using Arduino. What to show is transported from my web server. The character is stored as a 16x16 dot matrix, needing 16*16/8=32 byte. And I need to show some sentences, which contains more than 100 Chinese characters. </p> <p>The problem is that I can't storage all the dot matrix data in Arduino because it has too small memory.</p> <ul> <li>If I get the dot matrix data from web server, I need to have 100*32B memory, but SPAM with EEPROM have only 3k. So that failed.</li> <li>If I save the dot matrix "library" in the Flash memory, I need 3500*32B (There are 3500 Chinese frequent-used characters), but there is only 32K Flash. Saving the "library" means that I should storage the dot matrix data of all the 3500 chars in Flash, then the server only need to send the Unicode of characters, and I can get the matrix of the char.</li> </ul> <p>Any help is appreciated!</p>
<p>The basic EEPROM write, each 1 byte, as is mentioned in the above answer.</p> <p><a href="http://www.hobbytronics.co.uk/arduino-external-eeprom" rel="nofollow">http://www.hobbytronics.co.uk/arduino-external-eeprom</a></p> <p>The PAGE WRITE which is suitable for this situation. One can easily read 32 bytes for a dot matrix.</p> <p><a href="http://www.hobbytronics.co.uk/eeprom-page-write" rel="nofollow">http://www.hobbytronics.co.uk/eeprom-page-write</a></p>
11682
|arduino-uno|arduino-mega|sensors|
Improve sampling speed while using a multiplexer
2015-05-09T13:36:32.303
<p>I currently connected 5 sensor via a multiplexer (I must connect them to a multiplexer because they are I2C devices but they cannot been allocate more then 2 addresses so I use a multiplexer to solve the addressing problem).</p> <p>However the sample rate is a shame , it is about 6.5Hz . I wish I could improve the sample rate by using some tricks. In my loop() function, multiplexer will loop through channel 0-4 , and read each of these channel's sensor value and print it by using Serial.print()</p> <p>Is there any tricks I could use to improve my sampling rate faster ? Thanks...</p> <p>Here is my multiplexer class :</p> <pre><code>class MUX { public: //mux control pins: int s0 = 22; int s1 = 24; int s2 = 26; int s3 = 28; //SIG pin (not necessary WHEN sig is connect to 5V) //int SIG_pin = 0; //array to store channel :: muxChannel[channel numbers ][4 digit channel representation] int muxChannel[16][4] = { {0, 0, 0, 0}, //channel 0 {1, 0, 0, 0}, //channel 1 {0, 1, 0, 0}, //channel 2 {1, 1, 0, 0}, //channel 3 {0, 0, 1, 0}, //channel 4 {1, 0, 1, 0}, //channel 5 {0, 1, 1, 0}, //channel 6 {1, 1, 1, 0}, //channel 7 {0, 0, 0, 1}, //channel 8 {1, 0, 0, 1}, //channel 9 {0, 1, 0, 1}, //channel 10 {1, 1, 0, 1}, //channel 11 {0, 0, 1, 1}, //channel 12 {1, 0, 1, 1}, //channel 13 {0, 1, 1, 1}, //channel 14 {1, 1, 1, 1} //channel 15 }; void setupMux() { pinMode(s0, OUTPUT); pinMode(s1, OUTPUT); pinMode(s2, OUTPUT); pinMode(s3, OUTPUT); digitalWrite(s0, LOW); digitalWrite(s1, LOW); digitalWrite(s2, LOW); digitalWrite(s3, LOW); Serial.println(F("Multiplexer initialized")); } void selectChannel(int channel) { int controlPin[] = {s0, s1, s2, s3}; for (int i = 0; i &lt; 4; i++) { digitalWrite(controlPin[i], muxChannel[channel][i]); } } </code></pre>
<p>The technique suggested by @JRobert (starting all the conversions in one loop, then running another loop to wait for completions and read results) looks reasonable.</p> <p>Here are a couple of ways to shorten the code shown in the question:</p> <p>First, instead of four <code>int</code> declarations to set the value of <code>s0 ... s3</code>, use an <code>enum</code>. An <code>enum</code> is used to declare integer constants.</p> <pre><code>enum { s0 = 22, s1 = 24, s2 = 26, s3 = 28}; </code></pre> <p>Second, don't bother with the lengthy, tedious, and unnecessary <code>muxChannel</code> array. Delete the declaration of <code>muxChannel</code> and replace <code>selectChannel</code> with the following:</p> <pre><code>void selectChannel(int channel) { int controlPin[] = {s0, s1, s2, s3}; for (int i = 0; i &lt; 4; i++) { digitalWrite(controlPin[i], channel &amp; 1); channel /= 2; } } </code></pre> <p>The expression <code>channel &amp; 1</code> picks off the least-significant-bit of <code>channel</code>. The statement <code>channel /= 2;</code> divides <code>channel</code> by 2, which moves the next bit of <code>channel</code> into place for output. You could instead say <code>channel &gt;&gt;= 1;</code> or <code>channel = channel/2;</code>, etc. if you prefer.</p> <p>You might also look closely at your sensor boards to see if there is any way to add jumpers to get another bit or two of I2C device addressing, allowing you to avoid multiplexing.</p>
11691
|programming|c|
Why doesn't my code work in a function, yet works inline?
2015-05-10T11:18:44.960
<p>I'm trying to write a faster <code>shiftOut</code> function, which does not use the slow <code>digitalWrite</code>. In my code I have the original <code>shiftOut</code>, the new shiftOutFast, and the same as shiftOutFast, but inline. The three blocks are separated by delays to tell them apart on my scope. Here's the code: </p> <pre><code>#define CLR(x,y) (x &amp;= (~(1 &lt;&lt; y)) ) #define SET(x,y) (x |= (1 &lt;&lt; y) ) void shiftOutFast(uint8_t dataPort, uint8_t dataBit, uint8_t clkPort, uint8_t clkBit, uint8_t bitOrder, uint8_t val) { for (uint8_t i = 0; i &lt; 8; i++) { if (bitOrder == LSBFIRST) { if (val &amp; 0x01) { SET(dataPort, dataBit); } else { CLR(dataPort, dataBit); } val &gt;&gt;= 1; } else { if (val &amp; 0x80) { SET(dataPort, dataBit); } else { CLR(dataPort, dataBit); } val &lt;&lt;= 1; } CLR(clkPort, clkBit); SET(clkPort, clkBit); } } #define dataPin 4 #define clockPin 5 #define dataPort PORTD #define dataBit PORTD4 #define clockPort PORTD #define clockBit PORTD5 void setup() { pinMode(dataPin, OUTPUT); pinMode(clockPin, OUTPUT); } void loop() { shiftOut(dataPin, clockPin, LSBFIRST, 0x55); delay(1); shiftOutFast(dataPort, dataBit, clockPort, clockBit, LSBFIRST, 0x5C); delay(1); bool bitOrder = LSBFIRST; uint8_t val = 0x5C; for (uint8_t i = 0; i &lt; 8; i++) { if (bitOrder == LSBFIRST) { if (val &amp; 0x01) { SET(dataPort, dataBit); } else { CLR(dataPort, dataBit); } val &gt;&gt;= 1; } else { if (val &amp; 0x80) { SET(dataPort, dataBit); } else { CLR(dataPort, dataBit); } val &lt;&lt;= 1; } CLR(clockPort, clockBit); SET(clockPort, clockBit); } delay(1); } </code></pre> <p>The problem is that calling <code>shiftOutFast</code> doesn't do zilch. Absolutely nothing. It doesn't seem to be the logic, because when I do the same inline it works. Any ideas?</p>
<p>The problem is that you are passing the value of the ports to the function, not the address of the ports.</p> <p>You need to either pass "by reference" or as a pointer, so that modifying the port variable modifies the <em>actual</em> port variable not the copy of the value that you pass.</p> <p>The simplest way is to modify your function to be:</p> <pre><code>void shiftOutFast(volatile uint8_t &amp;dataPort, uint8_t dataBit, volatile uint8_t &amp;clkPort, uint8_t clkBit, uint8_t bitOrder, uint8_t val) { .... } </code></pre> <p>That way, instead of passing whatever is in the port at the time to the function (pass by value) it instead creates a new variable which is located at the same address as the variable that you are passing (pass by reference) so modifications of one variable modifies the other.</p> <p>Note that only the "port" variables need to be passed by reference, all the others remain as pass by value. Also they should be, as Edgar says, flagged as <em>volatile</em>.</p>
11694
|arduino-uno|nrf24l01+|
OTA updates for Arduino using nRF24L01+
2015-05-10T13:31:43.463
<p>Is it possible to send OTA updates to Arduino via nRF24L01+ module?</p> <p>Here are my findings:</p> <p><a href="http://www.instructables.com/id/Wireless-upload-program-to-Arduino-without-USB-cab/" rel="noreferrer">Here</a> is an instructable explaining how to program Arduino wirelessly but this thing uses a BT module which shows up on PC as a COM port.</p> <p><a href="http://www.instructables.com/id/Arduino-Wireless-Programming-with-XBee-Series-1-or/?ALLSTEPS" rel="noreferrer">Here</a> is something similar using Xbees.</p> <p>However, these use another arduino attached to a PC on the other end. In my case, I am planning to use rPi hooked to another nRF24L01+ rather than PC.</p> <p>This is an excerpt from the datasheet of Atmega chip:</p> <blockquote> <p>In ATmega88A/88PA/168A/168PA/328/328P the Boot LoaderSupport provides a real Read-While-Write SelfProgramming mechanism for downloading and uploading program code by the MCU itself. This feature allows flexible application software updates controlled by the MCU using a Flash-resident Boot Loader program. The Boot Loader program can use any available data interface and associated protocol to read code and write (program) that code into the Flash memory, or readthe code from the program memory.</p> </blockquote> <p>Here is what I planned as a strategy.</p> <p>Master programmer = Raspberry Pi + nRF module.</p> <p>Slave arduino = Arduino + nRF24L01 + external EEPROM</p> <p>Once I have to upload a new code, I can transmit the compiled code to the arduino (I can do that, right?) and Arduino will save it in the external EEPROM for the time being.</p> <p>When the transfer is complete, I will send a signal which will make the arduino reset and copy the code from EEPROM to its flash memory.</p> <p>My questions:</p> <p>Is the strategy correct and feasible?</p> <p>How should I proceed to achieve it?</p> <p>Any other suggestions which you might have are welcome.</p>
<p>As per @Majenko and @Kurt suggestions:</p> <p>Please check out me blog post, it is exactly about that!</p> <p><a href="https://www.2bitornot2bit.com/blog/arduino-bootloader-with-ota-over-the-air-support-over-nrf24l01" rel="nofollow noreferrer">https://www.2bitornot2bit.com/blog/arduino-bootloader-with-ota-over-the-air-support-over-nrf24l01</a></p> <p>I have made a complete tutorial about this issue and also modified the suggested code above so debugging will be easier.</p> <p>The basic idea is to have a local station which forwards the new sketch from the <strong>computer->uart->spi->rf24</strong> to a remote Arduino running a custom bootloader which listens on the <strong>rf24->spi</strong> instead of the UART. This bootloader does everything as usual (expecting protocol commands as part of the stk500 protocol and so on) but, instead of getting them over UART the packets arrive from the RF24 module through SPI. </p> <p>During boot, the bootloader will have to initialize the RF module registers and then parse the incoming bytes if any; after a timeout, it will quit and run the sketch currently there in a loog as usual</p> <p>In <a href="https://www.2bitornot2bit.com/home/arduino-bootloader-with-ota-over-the-air-support-over-rf24" rel="nofollow noreferrer">my blog</a> you will see some notes about the Hardware configuration for the local station: you need a 10uF capacitor between the <strong>RESET</strong> and <strong>GND</strong> pins to avoid flashing the local station while trying to flash the remote station. </p> <p>That post also incldues the commands needed to use AVRdude to flash the bootloader and then to flash the remote station (which has the new bootlaoder) through the local station running the "flasher" sketch (station with the capacitor).</p> <p>Basic commands are:</p> <pre><code>avrdude -C "C:\Users\Ben\Downloads\avrdude\etc\avrdude.conf" -b 19200 -c usbtiny -p m328p -v -e -U efuse:w:0xFD:m -U hfuse:w:0xDA:m -U lfuse:w:0xFF:m -F avrdude -C "C:\Users\Ben\Downloads\avrdude\etc\avrdude.conf" -b 19200 -c usbtiny -p m328p -v -e -U flash:w:optiboot_atmega328_new_bootlader.hex -U lock:w:0x0F:m </code></pre> <p>You can find the code on my blog and links to other sources and tools needed (such as an AVR programmer).</p>
11716
|led|
Passing VAL(0-179) to OLED
2015-05-11T11:45:57.787
<p>I´m using Spark Fun Micro Pro board 5V: <a href="https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/hardware-overview-pro-micro" rel="nofollow">https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/hardware-overview-pro-micro</a></p> <p>and to that i´ve hooked a true color OLED from digole: <a href="http://www.digole.com/index.php?productID=859" rel="nofollow">http://www.digole.com/index.php?productID=859</a></p> <p>I manage to get my VAL from my potentiometer on screen. But when I exceeds val "10", and then go back to lets say "9", the zero from "10" is still there. It looks like: "90" instead of "9". The problem is of course that the second (and third) number don't go away.. Im sure there is a simple way of doing this but I can't get my head around it.. I´ve tried using clearScreen but that function makes the OLED blink in a unpleasant way every time it clears... Hope you get my question, english isn't my native language, as u maybe can tell =) Thanks</p> <pre><code>void loop() { val = analogRead(potpin); // reads the value of the potentiometer (value between 0 and 1023) val = map(val, 0, 1023, 0, 179); // scale it to use it with the servo (value between 0 and 180) myservo.write(val) sets the servo position according to the scaled value mydisp.clearScreen(); mydisp.setPrintPos(9, 6); mydisp.print(val); delay(200); // waits for the servo to get there // mydisp.clearScreen(); } </code></pre>
<p>Instead of printing "10" or "9" etc, print "10 " or "9 ". Add an extra space at the end of what you print which overwrites the character that was there before.</p> <pre><code>mydisp.print(val); mydisp.print(" "); </code></pre> <p>I used 2 spaces there, in case you go from 3 digits straight to 1.</p> <p>Another method is to "format" the number using sprintf:</p> <pre><code>char temp[4]; sprintf(temp, "%3d", val); mydisp.print(temp); </code></pre>
11729
|arduino-ide|
Using Arduino command line on windows
2015-05-11T16:25:04.993
<p>I have an nmake file;</p> <pre><code> srcpath = ..\pilot cmdline = "C:\Program Files (x86)\Arduino\arduino.exe" cmdflags = --verify --board arduino:avr:uno --port com4 -v --preserve-temp-files prefs = --pref sketchbook.path=$(srcpath) --pref build.path=build deps = $(srcpath)\pilot.ino $(srcpath)\commands.h $(srcpath)\publish.h $(srcpath)\motor.h pilot.hex :$(deps) type $(srcpath)\pilot.ino $(cmdline) $(cmdflags) $(prefs) $(srcpath)\pilot.ino </code></pre> <p>The file types out fine, but Arduino returns an error;</p> <p>"failed to open sketch ..\pilot\pilot.ino"</p> <p>I am setting --pref sketchbook.path=$(srcpath), but I have tried with and without (and many variations of both) and get the same error.</p> <p>This is the command that is currently being invoked, and looks correct to me;</p> <pre><code>"C:\Program Files (x86)\Arduino\arduino.exe" --verify --board arduino:avr:uno --port com4 -v --preserve-temp-files --pref sketchbook.path=..\pilot --pref build.path=build ..\pilot\pilot.ino </code></pre> <p>Any ideas?</p>
<pre><code>srcPath = C:\Users\mikep\Documents\MWPRobotics\Pilot\Pilot bldPath = $(srcPath)\build arduinoCmd = "C:\Program Files (x86)\Arduino\arduino.exe" arduinoFlags = --verify --board arduino:avr:uno --port com4 -v --preserve-temp-files --preferences-file $(bldPath)\pilotPrefs.txt prefs = --pref sketchbook.path=$(srcPath) --pref build.path=$(bldPath) deps = $(srcPath)\Pilot.ino $(srcPath)\commands.h $(srcPath)\publish.h $(srcPath)\motor.h pilot.hex : $(deps) # type $(srcPath)\Pilot.ino $(arduinoCmd) $(arduinoFlags) $(prefs) $(srcPath)\Pilot.ino </code></pre> <p>Apparently it is really picky about absolute full paths (contrary to the comments that say it is relative)</p>
11730
|arduino-uno|ethernet|temperature-sensor|
DHT11 with Mysql
2015-05-11T16:45:55.620
<p>I need help to record databаse from dht11 sensor to mysql server. this is my code:</p> <pre><code>#include &lt;DHT.h&gt; #include &lt;Ethernet.h&gt; #include &lt;SPI.h&gt; byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // RESERVED MAC ADDRESS EthernetClient client; IPAddress server(192,168,0,102); // IP Adres (or name) of server to dump data to #define DHTPIN 2 // SENSOR PIN #define DHTTYPE DHT11 // SENSOR TYPE - THE ADAFRUIT LIBRARY OFFERS SUPPORT FOR MORE MODELS DHT dht(DHTPIN, DHTTYPE); long previousMillis = 0; unsigned long currentMillis = 0; long interval = 250000; // READING INTERVAL float temperature = 0; // TEMPERATURE VAR float humidity = 0; // HUMIDITY VAR String data; void setup() { Serial.begin(115200); if (Ethernet.begin(mac) == 0) { Serial.println("Failed to configure Ethernet using DHCP"); } dht.begin(); delay(10000); // GIVE THE SENSOR SOME TIME TO START temperature = (float) dht.readTemperature(); humidity = (float) dht.readHumidity(); } void loop(){ currentMillis = millis(); if(currentMillis - previousMillis &gt; interval) { // READ ONLY ONCE PER INTERVAL previousMillis = currentMillis; temperature = (float) dht.readTemperature(); humidity = (float) dht.readHumidity(); } if (client.connect(server, 3306)) { Serial.print("temperature=" ); Serial.println( temperature ); Serial.print("humidity=" ); Serial.println( humidity ); Serial.println("-&gt; Connected"); if(client.connected()){ // Make a HTTP request: client.print( "GET /add_data.php?"); client.print("temperature="); client.print( temperature); client.print("humidity="); client.print( humidity); client.println( " HTTP/1.1"); client.println( "Host: 192.168.0.102" ); //client.println(server); client.println( "Connection: close" ); client.println(); client.println(); client.stop(); } } if (client.connected()) { client.stop(); // DISCONNECT FROM THE SERVER } delay(30000); // WAIT FIVE MINUTES BEFORE SENDING AGAIN } </code></pre> <p>I connected to database but can't make records. this is output on serial monitor: temperature=21.00 humidity=73.00 -> Connected</p> <p>this is my php:add_data.php</p> <pre><code>&lt;?php // Connect to MySQL include("dbconnect.php"); // Prepare the SQL statement $SQL = "INSERT INTO test.test.temperature (temperature ,humidity) VALUES ('".$_GET["temperature"]."', '".$_GET["humidity="]."')"; // Execute SQL statement mysql_query($SQL); // Go to the review_data.php (optional) header("Location: review_data.php"); ?&gt; </code></pre> <p>dbconnect.php=></p> <pre><code>&lt;?php $MyUsername = "root"; // enter your username for mysql $MyPassword = "fifa2005"; // enter your password for mysql $MyHostname = "localhost"; // this is usually "localhost" unless your database resides on a different server $dbh = mysql_pconnect($MyHostname , $MyUsername, $MyPassword); $selected = mysql_select_db("test",$dbh); ?&gt; </code></pre> <p>review_data.php=></p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Arduino Temperature Log&lt;/title&gt; &lt;style type="text/css"&gt; .table_titles, .table_cells_odd, .table_cells_even { padding-right: 20px; padding-left: 20px; color: #000; } .table_titles { color: #FFF; background-color: #666; } .table_cells_odd { background-color: #CCC; } .table_cells_even { background-color: #FAFAFA; } table { border: 2px solid #333; } body { font-family: "Trebuchet MS", Arial; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Arduino Temperature Log&lt;/h1&gt; &lt;table border="0" cellspacing="0" cellpadding="4"&gt; &lt;tr&gt; &lt;td class="table_titles"&gt;ID&lt;/td&gt; &lt;td class="table_titles"&gt;Date and Time&lt;/td&gt; &lt;td class="table_titles"&gt;Temperature&lt;/td&gt; &lt;td class="table_titles"&gt;Humidity&lt;/td&gt; &lt;/tr&gt; &lt;?php // Retrieve all records and display them $result = mysql_query("SELECT * FROM temperature ORDER BY id ASC"); // Used for row color toggle $oddrow = true; // process every record while( $row = mysql_fetch_array($result) ) { if ($oddrow) { $css_class=' class="table_cells_odd"'; } else { $css_class=' class="table_cells_even"'; } $oddrow = !$oddrow; echo '&lt;tr&gt;'; echo ' &lt;td'.$css_class.'&gt;'.$row["id"].'&lt;/td&gt;'; echo ' &lt;td'.$css_class.'&gt;'.$row["timestamp"].'&lt;/td&gt;'; echo ' &lt;td'.$css_class.'&gt;'.$row["temperature"].'&lt;/td&gt;'; echo ' &lt;td'.$css_class.'&gt;'.$row["humidity"].'&lt;/td&gt;'; echo '&lt;/tr&gt;'; } ?&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p>i'm not sure why my old code doesn't work, but this is my new one and it is working fine. Maybe it will help someone.</p> <pre><code>#include &lt;dht.h&gt; #include &lt;SPI.h&gt; #include &lt;Ethernet.h&gt; EthernetClient client; byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; char server[] = "192.168.0.101"; dht DHT; int interval = 5000; // Wait between dumps #define DHT11_PIN 2 void setup() { Ethernet.begin(mac); Serial.begin(115200); //Serial.println("Humidity (%),\tTemperature (C)"); } void loop() { Serial.print("Temperature2 = "); Serial.print(DHT.temperature); Serial.println(" *C"); Serial.print("Humidity = "); Serial.print(DHT.humidity); Serial.println(" "); // READ DATA //Serial.print("DHT11, \t"); int chk = DHT.read11(DHT11_PIN); if (client.connect(server, 80)) { client.print( "GET /diplomna/Arduino/add_data.php?"); client.print("temperature=");; client.print( DHT.temperature ); client.print("&amp;&amp;"); client.print("humidity="); client.println( DHT.humidity ); client.println( "HTTP/1.1"); client.println( "Connection: close" ); client.stop(); Serial.println("CONNECTED"); } else { // you didn’t get a connection to the server: Serial.println("–&gt; connection failed/n"); } delay(interval); } </code></pre>
11735
|xbee|
connection between two ARDUINO with xbee
2015-05-11T10:44:11.013
<p>I have a setup where two XBEES modules are talking to each other, both using XBEE shields, one attached to an UNO ARDUINO and the other a MEGA ARDUINO. One XBEE sends the data and the other receives it and switch on or off a LED. The problem is the receiver one don't work. This is the sender code </p> <pre><code>int led = 13; const int bouton = 2; String inputString; void setup() { pinMode(led, OUTPUT); Serial1.begin(9600); Serial.begin(9600); digitalWrite(led, LOW); } void loop() { while (Serial.available() ) { // get the new byte: delay(3); char inChar = Serial.read(); // add it to the inputString: inputString += inChar; } if (inputString.length() &gt;0) { Serial.println(inputString); Serial1.println(inputString); inputString=""; } } </code></pre> <p>This the receiver one </p> <pre><code>int led = 13; String inputString; void setup() { // put your setup code here, to run once: pinMode(led, OUTPUT); Serial.begin(9600); } void loop() { while (Serial.available() ) { // get the new byte: delay(3); char inChar = Serial.read(); // add it to the inputString: inputString += inChar; } if (inputString.length() &gt;0) { Serial.println(inputString); if (inputString == "on"){ digitalWrite(led,HIGH); Serial.println("LED ON"); } if (inputString == "off"){ digitalWrite(led,LOW); Serial.println("LED OFF"); } inputString=""; } } </code></pre> <p>I get on the serial monitor of ARDUINO UNO what i wrote in the serial monitor of ARDUINO MEGA but the LED don't switch on or off :/</p>
<p>Probably you are getting a new character/carrier return (\n or \n\r) in your receivers' string, that is why it won't match exactly "on" or "off", it will be "on\n", "on\r\n" or similar.</p>
11743
|usb|serial|ftdi|
Can the Arduino Due be used as a serial to USB converter?
2015-05-10T23:13:20.470
<p>The Arduino due exclusively runs on 3.3V, so I am wondering if this can be used as a USB to serial converter just like the Arduino Uno could, or do you need to do level shifting?? Will I ruin the board if I just hook up RX and TX to a 5v device?</p>
<p>Yes it will work as a USB to serial device, however the serial will be at 3.3V not 5V. It'll still be serial though.</p> <p>For it to send data to a 5V device, depending on the device, it might work. 3.3V is often around the "high" threshold for an input pin on a 5V device, but check the datasheet for the 5V device to be sure.</p> <p>For receiving data the 5V will be above the 3.3V supply voltage of the main SAM3X chip, so should be avoided. As with most Atmel datasheets, actually finding the information you want is almost impossible, and I haven't found if there is a maximum "over voltage input current" or not, so to be on the safe side a full level shifting voltage divider should be used on the RX pin.</p>
11754
|analogread|signal-processing|
Arduino Cross Correlation?
2015-05-12T09:31:45.340
<p>How can I write lightweight cross correlation code for arduino? I couldnt find any solution. The measurement system contains an ultrasonic sensor and a servo that turns from 45 to 135 degree and measures distance from 4-300 cm. Than i collect data in an array which contains distances with respect to angle. System makes several measurement like this and program finds cross correlation between new and old arrays.</p> <p><a href="http://www.instructables.com/id/How-To-Make-an-Obstacle-Avoiding-Arduino-Robot/" rel="nofollow">http://www.instructables.com/id/How-To-Make-an-Obstacle-Avoiding-Arduino-Robot/</a></p>
<p>Given the time scale of the measurements, performance is not an issue. And since you are not computing in real-time, as the samples are being measured, you can apply the definition of cross-correlation as is, and compute it in a double loop. The only difficulty is figuring out that cross-correlation may not be the proper tool for the job... and finding the right one! My assumption is that you want to estimate a rotation angle between the two measurements.</p> <p>The mathematical definition of cross-correlation assumes infinite arrays. In practice, cross-correlation is often used to locate a short pattern inside a long signal. In this case, the computation is done only for shifts where the pattern completely overlaps the signal. Then the length of the result is</p> <pre><code>length(result) = length(signal) − length(pattern) + 1 </code></pre> <p>In your case, since your pattern is a previously measured signal, this would give a single-sample result, which is useless.</p> <p>You could instead compute the integral for all shifts where there is <em>any</em> overlap between the pattern and the signal. This is equivalent to zero-padding the signal. This has the drawback of biasing the result: if your signal and pattern are both featureless (positive constants), you will find a very nice peak at zero shift!</p> <p>You can remove this bias by subtracting the average from both the signal and the pattern, and correlating (signal −&nbsp;avg(signal)) with (pattern −&nbsp;avg(pattern)). This still carries a bias for “big” features. Imagine for example that, after removing the averages, you have</p> <pre><code>pattern = [ 0, 0, −20, +20, 0, 0]; signal = [−50, +50, 0, 0, −20, +20]; </code></pre> <p>You would expect your correlator to find a good match between the [−20, +20] of the pattern and the [−20, +20] of the signal. The correlation is, however, much better with the [−50, +50] of the signal. You may try to alleviate this by computing a normalized cross-correlation instead, but you will at best make both matches equally good.</p> <p>My suggestion is that you completely forget about correlations and instead think in terms of “goodness of fit”. Correlations are good for finding scaled and shifted copies of a pattern inside a signal. You are looking for <em>shifted only</em> copies, with no scaling. Your question should be: if you shift the pattern by some amount, how well does it fit the signal? What amount of shift gives the better fit? The canonical answer to all “goodness of fit” questions is to minimize the RMS difference between the two: you compute the sum</p> <pre><code>S = Σ(signal − shifted(pattern))² </code></pre> <p>Then the RMS difference is</p> <pre><code>RMS(difference) = √(S/N) </code></pre> <p>where <em>N</em> is the number of samples involved in the sum. The most likely shift is the one that minimizes this error. In practice, you do not need the square root, you just minimize</p> <pre><code>RMS(difference)² = Σ(signal − shifted(pattern))² / N </code></pre> <p>You can implement this formula as-is, it's completely straightforward. Just beware that <em>N</em> depends on the shift, as it's the length of the overlap. And avoid going to very small overlaps (i.e. large shifts).</p> <p>Now, if you expand the square inside the sum, you may find that, after all, this is not so far from a cross-correlation... And BTW, all this has nothing to do with Arduino.</p>
11762
|pins|c|
Reading/writing to Arduino GPIO pins from raw C code
2015-05-12T17:00:07.477
<p>I'm interested in writing a C program <em>without</em> the Arduino IDE and related libraries and am trying to figure out how I can access the GPIO pins for read and write.</p> <p>My <em>assumption</em> is that the GPIO pins are - at the hardware layer - just memory addresses, and so if I know what their address is I can send/receive data to and from them.</p> <ul> <li>For writing to the digital pins, do I just send an <code>int</code> with a value of <code>0</code> or <code>1</code> to the pin's address? If so, what might that code look like? Can I then assume I could poll that address for a value, which would be either <code>0</code> or <code>1</code>?</li> <li>Can I assume the same for analog pins, but instead of binary values, I'd get an integral value between <code>0</code> and <code>1023</code>?</li> </ul> <p>And if I'm way off here, and pins are <em>not</em> accessed via memory addresses, then how?</p> <p>Again, the solution I'm looking for wouldn't involve Arduino software, just the Arduino hardware (an AVR or ARM MCU). Bonus points for C pseudo-code examples! Thanks in advance!</p>
<p>In theses cases you are right, using register address is the way to read/write data from/to digital pins. In the case you use analog input, the process is similar but you have to follow some procedures before getting the value of the data.</p> <p><strong><a href="https://techawarey.wordpress.com/2013/12/28/avr-gpio-tutorial/" rel="nofollow">GPIO REGISTERS</a></strong></p> <p>For AVR micro-controllers these registers are: DDRn – Data Direction Register PORTn – Port Output data Register PINn – Port Input Register n- Indicates the port name i.e. A, B, C &amp; D If you have arduino board and want to use these pins, look for mapping pictures about arduino and avr pins.</p> <p>The following is an example from the Arduino website.</p> <p>DDRD is the direction register for Port D (Arduino digital pins 0-7). The bits in this register control whether the pins in PORTD are configured as inputs or outputs so, for example: </p> <pre><code>DDRD = B11111110; // sets Arduino pins 1 to 7 as outputs, pin 0 as input DDRD = DDRD | B11111100; // this is safer as it sets pins 2 to 7 as outputs // without changing the value of pins 0 &amp; 1, which are RX &amp; TX </code></pre> <p>See the bitwise operators reference pages and The Bitmath Tutorial in the Playground</p> <p>PORTD is the register for the state of the outputs. For example;</p> <pre><code>PORTD = B10101000; // sets digital pins 7,5,3 HIGH </code></pre> <p>You will only see 5 volts on these pins however if the pins have been set as outputs either by using the <code>DDRD</code> register directly or by using the <code>pinMode()</code> function.</p> <p><strong>For analog read</strong></p> <p>You just need to include the headers and start using the registers. They hold the equivalent hexadecimal values for your microcontroller. And the procedure is described in the datasheet. All you have to do is to translate it to code.</p> <pre><code>// this code scans ADC1 for an analog signal upon request, using 8Mhz processor clock #include &lt;avr/io.h&gt; #include &lt;stdint.h&gt;       // needed for uint8_t int ADCsingleREAD(uint8_t adctouse) {     int ADCval;     ADMUX = adctouse;        // use #1 ADC     ADMUX |= (1 &lt;&lt; REFS0);   // use AVcc as the reference     ADMUX &amp;= ~(1 &lt;&lt; ADLAR); // clear for 10 bit resolution // 128 prescale for 8Mhz ADCSRA |= (1 &lt;&lt; ADPS2) | (1 &lt;&lt; ADPS1) | (1 &lt;&lt; ADPS0);     ADCSRA |= (1 &lt;&lt; ADEN);    // Enable the ADC     ADCSRA |= (1 &lt;&lt; ADSC);    // Start the ADC conversion     while(ADCSRA &amp; (1 &lt;&lt; ADSC)); // waits for the ADC to finish     ADCval = ADCL;     ADCval = (ADCH &lt;&lt; 8) + ADCval; // ADCH is read so ADC can be updated again     return ADCval; }     int main(void) {     int ADCvalue;     while (1)     {         ADCvalue = ADCsingleREAD(1);         // ADCvalue now contains an 10bit ADC read     } } </code></pre> <p>For more information about analog read, see <a href="https://sites.google.com/site/qeewiki/books/avr-guide/analog-input" rel="nofollow">this</a>.  </p>
11763
|wifi|
Wifi REST API GET call - how to concatenate and pass URL parameters?
2015-05-12T17:09:17.823
<p>I'm not too familiar with the Arduino C++ language, but I would like to get this native code to work.</p> <p>In curl this works:</p> <blockquote> <p>curl "<a href="http://access.alchemyapi.com/calls/text/TextGetTextSentiment?text=i+feel+great&amp;outputMode=json&amp;apikey=my-apikey" rel="nofollow">http://access.alchemyapi.com/calls/text/TextGetTextSentiment?text=i+feel+great&amp;outputMode=json&amp;apikey=my-apikey</a>"^C</p> </blockquote> <p>So I am trying to use a WiFi client for the same request but it seems the passing and parsing of the URL parameters is causing a problem.</p> <pre><code>sprintf(request,"/calls/text/TextGetTextSentiment?apikey=%s&amp;text=%s&amp;outputMode=%s","31adba6dfc3a879b88762f50efc9f892bd573207", "i+feel+great", "json"); Serial.println(request); </code></pre> <p>When I print the request, everything after the &amp; gets truncated.</p> <pre><code> char serverName[] = "access.alchemyapi.com"; if(client.connect(serverName,port) == 1) { sprintf(outBuf,"GET %s HTTP/1.1",page); client.println(outBuf); sprintf(outBuf,"Host: %s",serverName); client.println(outBuf); client.println(F("Connection: close\r\n")); } </code></pre> <p>This works (HTTP status 200, though with missing parameters error from the API service) if I only pass in 1 parameter. </p>
<p>Concatenating the string data in memory before sending it shouldn't be necessary. Instead, you should just be able to use <code>client.print()</code> (or equivalent) to output each part of the request in sequence. For example:</p> <pre><code>client.print("GET "); client.print(page); client.print(" HTTP/1.1\r\n"); client.print("Host: "); client.print(serverName); client.print("\r\n"); // etc. </code></pre> <p>That should let you output any combination of HTTP headers you need.</p>
11769
|gsm|gps|
Venus GPS + Arduino. Kill 3.3V TX during sketch upload
2015-05-12T18:14:50.223
<p>I am playing around with the Sparkfun Venus GPS. I followed <a href="http://www.doctormonk.com/2012/05/sparkfun-venus-gps-and-arduino.html" rel="nofollow" title="this">this</a> tutorial to get started. In here the author states that you should </p> <blockquote> <p>Upload the following sketch to your Arduino BEFORE making any connections. 5V from an IO pin left high on the Arduino may well kill the 3.3V output from the Tx pin on the GPS module.</p> </blockquote> <p>However, I am using the Sparkfun bi-directional logic level converter in between the Arduino and the Venus GPS (because I'm using the 5V Arduino GSM shield stacked on top of the Arduino). In that case, would the above statement still apply?</p>
<p>If you have a logic-converter between the Arduino and the GPS then you won't have any problems.</p> <p>The warning was about having the output from the Tx pin on the GPS possibly being damaged by +5 V from the Arduino, if a previously loaded sketch made it an output and HIGH.</p> <p>However you could just as easily upload a "do nothing" sketch like this:</p> <pre class="lang-C++ prettyprint-override"><code>int main () { } </code></pre> <p>That is sound practice anyway, if you are connecting up new hardware and are not sure what the currently-loaded sketch does.</p>
11773
|sensors|
Vibration sensor for arduino
2015-05-12T20:30:21.020
<p>I need vibration sensor for my project. I have found many sensors similar to <a href="https://www.sparkfun.com/products/9196" rel="nofollow">this one</a>. But it seems, that this sensor outputs only zeros for "non-hit" state and ones for "hit state". And I need something that can output levels of vibration, not only presence/abscense. </p> <p>So is there any high-resolution vibration sensor for arduino?</p> <p>Thank you!</p>
<p>The MPU-6050 is a very low-price 3 axis gyroscope and accelerometer with both SPI and I2C interface options. </p> <p>I found mine here: <a href="https://smile.amazon.com/gp/product/B00KKR9ORI" rel="nofollow noreferrer">https://smile.amazon.com/gp/product/B00KKR9ORI</a></p> <hr> <p>EDIT: Removed statement that it is accurate enough for this, based on comment.</p>
11775
|arduino-uno|bootloader|arduino-pro-mini|
Custom Bootloader on Atmega328p - PU - 28 pin DIP
2015-05-12T21:00:05.453
<p>I am experimenting with low-power wireless arduino modules. For that, I needed 3V powered arduino so that I can do away with voltage regulators which eat up a lot of battery juice.</p> <p>I am using 28 pin Atmega328p-PU dip IC with 8 MHz external crystal oscillator. Just for trying, I dumped the arduino pro mini 3.3V 8 MHz bootloader into it and it was a success. Everything is working as expected. However, I realized that SMD package which is being used in pro mini has 8 ADC pins compared to 6 in the DIP version.</p> <p>Should I be worried about it? </p> <p>Second feasible option is modifying the Arduino UNO board definition to use 8 MHz clock source as compared to 16 MHz and leave everything else same. Do you think this will serve my purpose?</p>
<p>The Atmega328p has 8 analog inputs. Some packages (such as the DIP) don't have enough pins to bring all of them out, but they are in there. The SMD package brings all of them out, but it apparently the Pro Mini does not pick up two of them. The net result is the same - 6 useable and 2 unusable analog inputs.</p>
11782
|arduino-uno|accelerometer|gyroscope|
Comparing orientation data obtained using gyroscope and accelerometer
2015-05-13T02:58:02.463
<p>Recently, I have been playing around with a gyroscope and accelerometer in the hopes of building a quadcopter. I have plotted some of the data the two sensors and I am noticing that the pitch from the accelerator lags significantly behind the gyroscopic pitch.</p> <p>From some research, I understand that these two are not going to equivalent values due to the mechanisms of measurement, however is it common to have such large discrepancies (i.e a difference of 20 degrees or higher) between the two sensors or is this an issue with my conversion? </p> <p>I have listed the graph and source code <a href="https://www.dropbox.com/sh/lemczvtzstgdhcj/AAAYqmxft7sWJ-tMkcKaA2d7a?dl=0" rel="nofollow">here</a>. Any help would be appreciated! </p> <p>Sincerely, Anand</p>
<p>Normally the values from gyroscope will drift overtime. It is natural and depends on the parameters of your code. It could drift a few degrees per seconds and the data will be far way from the accelerometer in a few seconds.</p> <p>I have seen that you have applied the complementary filter, so you don't need to worry about the single value from the gyros since you combine them with the acceleromter and everything seems fine.</p> <p>The gyros are good for short time response, in long time response the values get pretty bad as they drift a lot.</p> <p>On the other hand, accelerometers are good for long time response, since short time response is noisy because of gravitational influence.</p> <p>That's why you need a filter to combine them. </p> <p>Wrapping up, it is normal to have this behavior in gyros. If you want to know more about the effect behind this sensor, try this <a href="http://en.wikipedia.org/wiki/Coriolis_effect" rel="nofollow">reading</a>.</p>
11783
|arduino-uno|sensors|i2c|
Reading data from airspeed v3 eagle tree
2015-05-13T03:43:47.833
<p>I am trying to get values from this sensor <strong>Airspeed v3</strong> from eagle tree but it seems my I2C is not working properly.</p> <p>I bought a module in third party mode and followed these <a href="http://www.eagletreesystems.com/Manuals/microsensor-i2c.pdf" rel="nofollow">instructions</a> from the manufacturer website.</p> <p>I went to rcgroups forum and discovered the right values for the bits mentioned in the documentation about WRITE and READ.</p> <p>I started the development of a code but I cannot get the values from the sensor. It is supposed to send me a 2 byte-formatted value indicating the airspeed measured. But surprisingly when I call this method <code>Wire.requestFrom(AIRSPEED_ADDRESS, 2)</code> it returns 0, so someway the communication is not working. I have used I2C before for ADXL345 sensor and it works perfectly. </p> <p>The results from these lines </p> <pre><code>Serial.println(data[0]); Serial.println(data[1]); </code></pre> <p>are just -1 indicating that no data is available to display.</p> <p>Does anybody know how to get this working? Am I missing something?</p> <p>This is my code right now.</p> <pre><code>#include &lt;Wire.h&gt; #define AIRSPEED_ADDRESS 0xEA #define WRITE_BIT 0x00 #define READ_BIT 0x01 void setup() { // join I2C bus (I2Cdev library doesn't do this automatically) Wire.begin(); Serial.begin(9600); Serial.println("Program started"); } void loop() { byte data[2] = {0}; int i = 0; int16_t velocidade = 0; Wire.beginTransmission(AIRSPEED_ADDRESS); if (!Wire.write(WRITE_BIT)) { Serial.println("error sending write_bit"); } Wire.endTransmission(); Wire.beginTransmission(AIRSPEED_ADDRESS); if (!Wire.write(0x07)) { Serial.println("error sending 0x07"); } Wire.endTransmission(false); Wire.beginTransmission(AIRSPEED_ADDRESS); if (!Wire.write(READ_BIT)) { Serial.println("error sending read_bit"); } else { //Serial.println("ok sending read_bit"); } Wire.endTransmission(); Wire.beginTransmission(AIRSPEED_ADDRESS); Serial.print("bytes read from slave: "); Serial.println( Wire.requestFrom(AIRSPEED_ADDRESS, 2) ); data[0] = Wire.read(); data[1] = Wire.read(); Wire.endTransmission(); velocidade = data[1] | (data[0] &lt;&lt; 8); Serial.println(data[0]); Serial.println(data[1]); Serial.println(" "); } </code></pre>
<p>I found the I2C address on my Eagletree Airspeed V3 sensor to be 0x75 NOT 0xEA.</p> <p>the following code adapted from first sample above works on my Nano:</p> <pre><code>/* * note that timming is critical - see delay (5) * and bps set to 115200 * works ok, but clean up 5-19-2019 jaf */ #include &lt;Wire.h&gt; #define AIRSPEED_ADDRESS 0x75 #define WRITE_BIT 0x00 #define READ_BIT 0x01 void setup() { Wire.begin(); Serial.begin(115200); Serial.println("Program started"); } void loop() { byte data[2] = {0}; int i = 0; Wire.beginTransmission(AIRSPEED_ADDRESS); Wire.write(WRITE_BIT); Wire.endTransmission(); Wire.beginTransmission(AIRSPEED_ADDRESS); Wire.write(0x07); Wire.endTransmission(); Wire.beginTransmission(AIRSPEED_ADDRESS); Wire.write(READ_BIT); Wire.endTransmission(); Wire.beginTransmission(AIRSPEED_ADDRESS); Wire.requestFrom(AIRSPEED_ADDRESS, 2); data[0] = Wire.read(); Wire.endTransmission(); Serial.println(data[0]); delay(5); } </code></pre>
11785
|programming|servo|
How to control 2 servos at same time in sync?
2015-05-11T03:56:58.113
<p>For overcoming torque issues, I have attached 2 <em>identical</em> servos on a certain part of my robot arm <sub>and because I saw someone do the same.</sub></p> <p>Now, while writing code I realize:</p> <pre><code>#include &lt;Servo.h&gt; ... ... shoulder1.write(map(analogRead(p1), 0, 1023, 0, 179)); shoulder2.write(map(analogRead(p1), 0, 1023, 0, 179)); ... </code></pre> <p>will turn <code>shoulder1</code> by 20* and then <code>shoulder2</code> by another 20*, ie. an overall turn of 40*; that too with too much load on servos, as the other servo would be inactive at the time first is active.</p> <p>I want to achieve 20* fully-sync.ed turn on both servos, how do I accomplish this? Any arduino libraries or walkthrough?</p> <hr> <p>Can I possibly move them <a href="http://playground.arduino.cc/ComponentLib/servo" rel="nofollow">both at the same time</a> - something like <a href="http://forum.arduino.cc/index.php?topic=4854.0" rel="nofollow">multithreading</a> on arduino? Here's what I tried:</p> <pre><code>void rotateTwoServoInSync(int angle) { for(int i = 0; i&lt;angle; i++) { shoulder1.attach(9); shoulder1.write(i); shoulder1.detach(); shoulder2.attach(10); shoulder2.write(i); shoulder2.detach(); } } </code></pre> <p>Will it work? Is this approach recommendable?</p>
<p>To operate two or more servos at the same time you need to interpolate their movements, first moving one servo a little, then moving the next one, back and forth until all servos arrive at their destination point. I haven't seen a library yet that accomplishes this for you so you probably need to write your own routine. Here is a project where I interpolated three servos and includes the code: <a href="https://www.instructables.com/id/MonkeyBot-3-Servo-Climbing-Robot/" rel="nofollow noreferrer">https://www.instructables.com/id/MonkeyBot-3-Servo-Climbing-Robot/</a></p>
11791
|arduino-mega|sensors|power|
Do multiple ultrasonic sensors need an external power source?
2015-05-13T10:07:51.913
<p>So maybe it's a very low class form of question, but please bear with me. I'm working on a project with 7 HC-SR04 ultrasonic sensors connected to one Arduino. I tried to unify the trigger and echo pin, but the sensing isn't good enough, so I dropped the Uno and convert it to Mega. My question is, do I need external power source for those 7 Sensors? And how do I connect all of them? Thanks</p>
<p>You will probably not have any kind of problem with the Arduino power source, while in the test bench. When using it for the Drone/Bot you seem to be working, make sure to have a stable power source to the Arduino, and, if possible, let your sensors have their own energy input.</p> <p>I had previous experiences with the sensors not working properly because the Arduino was not getting enough energy through the Arduino's pins when mounted.</p>
11794
|serial|processing-lang|
Sending serial data to Processing
2015-05-13T12:12:20.580
<p>I have a question about using the Arduino and Processing. I want to build a touch sensor using aluminum foil and connect it to an interface built in Processing. However i've come across a problem. I don't know how to send the serial data from the Arduino to Processing. This is the code I'm using to get the sensor value from the aluminum foil:</p> <pre><code>#include &lt;CapacitiveSensor.h&gt; CapacitiveSensor cs_4_2 = CapacitiveSensor(4,2); void setup(){ Serial.begin(9600); } void loop(){ long start = millis(); long total1 = cs_4_2.capacitiveSensor(30); Serial.print(millis() - start); Serial.print("\t"); Serial.print(total1); Serial.print("\t"); Serial.print('\n'); delay(100); } </code></pre> <p>The foil is connected to dig pin 4 with a resistor of 1M in between and to dig pin 2 with a resistor of 1K. Pin 4 is the send pin, pin 2 is the receive pin. It all works just fine, in the serial monitor in the Arduino software I get the value of the time between refreshes and the sensor value. But how do I use this sensor value in a Processing sketch? I thought of maybe using Firmata on the Arduino, but then I wouldn't know how to use the CapacitiveSensor library and get the sensor values. Does anyone know how to get this to work? Help would be greatly appreciated!</p>
<p>Try to use this code:</p> <pre><code>// Graphing sketch import processing.serial.*; Serial myPort; // The serial port int xPos = 1; // horizontal position of the graph void setup () { // set the window size: size(400, 300); // List all the available serial ports println(Serial.list()); // I know that the first port in the serial list on my mac // is always my Arduino, so I open Serial.list()[0]. // Open whatever port is the one you're using. myPort = new Serial(this, Serial.list()[0], 9600); // don't generate a serialEvent() unless you get a newline character: myPort.bufferUntil('\n'); // set inital background: background(0); } void draw () { // everything happens in the serialEvent() } void serialEvent (Serial myPort) { // get the ASCII string: String inString = myPort.readStringUntil('\n'); if (inString != null) { // trim off any whitespace: inString = trim(inString); // convert to an int and map to the screen height: float inByte = float(inString); inByte = map(inByte, 0, 1023, 0, height); // draw the line: stroke(127,34,255); line(xPos, height, xPos, height - inByte); // at the edge of the screen, go back to the beginning: if (xPos &gt;= width) { xPos = 0; background(0); } else { // increment the horizontal position: xPos++; } } } </code></pre> <p>Also look at: <a href="http://www.arduino.cc/en/Tutorial/Graph" rel="nofollow">http://www.arduino.cc/en/Tutorial/Graph</a></p>
11797
|arduino-nano|pwm|remote-control|
How to make an RC mixer with the arduino
2015-05-13T12:30:54.630
<p>I want to make a RC mixer mixing two channels of a receiver.</p> <p>What I have: a delta model plane, two servos, a receiver and a Arduino Nano.</p> <p>So I'd like to mix the aileron (two channels) with the elevator(one channel).</p> <p>EDIT: What I've done: I read the input of the receiver and wrote it to the servos. The problem: The servo stutters and the arduino displays false inputs.</p> <pre><code>int pin = A0; int pin1 = A1; unsigned long duration; unsigned long dur; unsigned long duration2; unsigned long dur2; #include &lt;Servo.h&gt; Servo myservo; Servo myservo2; void setup() { Serial.begin(9600); myservo.attach(9); } void loop() { duration = pulseIn(pin, HIGH); dur = duration; Serial.println(dur); myservo.writeMicroseconds(dur); delay(50); // duration2 = pulseIn(pin1, HIGH); // dur2 = duration2-980/4-200; // Serial.println(dur2); // myservo2.write(dur2); } </code></pre>
<p>You do not need to use long for values from pulseIn, using int will be sufficient.</p> <p>Your code is not complete, at least there is a missing '}' at the end of setup.</p> <p>The slower the baud rate (9600) actually the more it interferes with timing code, to a point. PWM is all timing code. I would suggest 57,600.</p> <p>You never set the servos to any pins. And is using Servo lib needed? I have always used <a href="http://www.arduino.cc/en/Reference/analogWrite" rel="nofollow">analogWrite</a> with no problems.</p> <p>You are not using parenthesis on your math (currently commented). It will not give you the result you expect. But you are somewhat on the right track, subtract 1500 from each pulse read, that will give you -/+ range. How you mix that depends on how your radio is setup (servo reversing, which channel is which). Keep in mind ailerons is 1 channel, so left aileron = -rightAileron. Elevator up = that + elevator. so;</p> <p>aileronLeft = airleronChannel + elevatorChannel<br> aileronRight = -airleronChannel + elevatorChannel</p> <p>You do realize this a <a href="http://www.hobbyking.com/hobbyking/store/__6321__TURNIGY_V_Tail_Mixer_Ultra_small.html" rel="nofollow">$3 part</a>?</p> <p>update: I have always used analogWrite, but I also always use good equipment. I see cautions that cheapo servos might be damaged with analogWrite. You can read more <a href="http://forum.arduino.cc/index.php?topic=5701.0" rel="nofollow">here</a>. It has always worked for me.</p>
11800
|serial|arduino-mega|softwareserial|rfid|
How to avoid pulling the RX0 pin to reset sketch
2015-05-13T13:23:45.037
<p>My project requires reading 5 serial devices (RFID readers) at the same time. I chose an Arduino Mega 2560 as it comes with 4 serial RX ports. For the fifth port I am using the SoftwareSerial library.</p> <p>My loop() checks each Serial port to detect if an RFID tag is being read. This works perfectly.</p> <p>However, I am powering the board from an wall wart. When the power is disconnected the sketch no longer runs. I must unplug RX0, plug in the power supply, and reattach RX0.</p> <p>If the board ever loses power it will have to be reset manually which is not ideal.</p> <p>Please help me understand Why is this happening? and how can I fix it?</p>
<p>You can simply disable the bootloader rather than erasing it. Find out the current fuse settings using a fuse-detection program. Change the BOOTRST flag in the High fuse to be unchecked, referring to this page: <a href="http://www.engbedded.com/fusecalc" rel="nofollow">Engbedded Atmel AVR® Fuse Calculator</a></p> <p>Write the High fuse back. Then it will ignore the bootloader and go straight to your code. Of course, to upload a new version you will have to put the BOOTRST fuse back, or you won't be able to use the bootloader to upload a new sketch.</p> <p>One way of changing the fuse is to use my <a href="http://www.gammon.com.au/uploader" rel="nofollow">Atmega chip stand-alone programmer sketch</a>. This has an interactive "change fuses" option. To run this you just need a spare board (eg. a Uno) and 6 wires to connect the programming board to your target Mega2560.</p> <p>Example wiring shown on the linked page. Note that you do <strong>not</strong> need the SD board to merely change fuses. Just the two Arduinos and the connecting wires are enough for that.</p> <p>When you first run the sketch it should inform you of the current fuses. Look at the High fuse and follow my instructions above.</p> <p>You should see something like this:</p> <pre><code>Entered programming mode OK. Signature = 1E 98 01 Processor = ATmega2560 Flash memory size = 262144 LFuse = FF HFuse = D8 EFuse = FD Lock byte = FF Bootloader in use: Yes </code></pre> <p>In this case the High fuse was D8, which has the bootloader enabled. Using the Fuse Calculator site we can see that it should now be D9 which disables the bootloader.</p> <hr> <p>An alternative way to change the fuse is to use Avrdude, if you have a stand-alone ISP programmer handy.</p>
11803
|serial|arduino-due|debugging|uart|flash|
What protocols and tools does Arduino Due use for flashing and debugging?
2015-05-13T15:25:00.160
<p>I am interested in writing a simple C program <em>outside</em> of the Arduino IDE and respective libraries, but deploying it directly to an Arduino Due (which uses a SAM3X8E ARM MCU). I am trying to figure out what comms/serial protocols are used for:</p> <ul> <li>Flashing/deploying the program to the ARM MCU; and</li> <li>Connecting the program to a debugger</li> </ul> <p>And, not just the protocols used, but what <em>tools</em> are compatible with these protocols, and henceforth, can be used for both use cases. How can I tell what my viable options are?</p>
<p>The Due (more specifically the SAM3X) uses its own proprietary protocol. It's all embedded in the bootloader, which is hard wired in the ROM and can never be changed (idiotic if you ask me).</p> <p>I know of two systems for communicating with it. Atmel's SAM-BA program, and the open source <a href="http://www.shumatech.com/web/products/bossa" rel="nofollow">BOSSA</a>. The command line version of BOSSA (bossac) is used by the Arduino IDE for programming.</p>
11821
|arduino-uno|
Disturbed digital out at 4Mhz on Arduino NANO
2015-05-14T08:04:02.643
<p>I've written a simple program - it generates signals over <code>Port D</code> at 4 MHz:</p> <pre><code>#include &lt;Arduino.h&gt; int main(void) { DDRD = B11111111; PORTD = B00000000; while (true) { PORTD = 0; PORTD = 5; PORTD = 10; PORTD = 15; PORTD = 20; PORTD = 25; PORTD = 30; PORTD = 35; PORTD = 40; } return 0; } </code></pre> <p>and this is the signal coming out on D4: <img src="https://i.stack.imgur.com/O3IfR.jpg" alt="Max Frequency"></p> <p>I've modified the program by inserting NOP after each assignment to <code>POTRD</code>:</p> <pre><code>#define NOP __asm__ __volatile__ ("nop\n\t") int main(void) { DDRD = B11111111; PORTD = B00000000; while (true) { PORTD = 0;NOP; PORTD = 5;NOP; PORTD = 10;NOP; PORTD = 15;NOP; PORTD = 20;NOP; PORTD = 25;NOP; PORTD = 30;NOP; PORTD = 35;NOP; PORTD = 40;NOP; } return 0; } </code></pre> <p>and now signal looks fine, but frequency is limited to 800 KHz: <img src="https://i.stack.imgur.com/gKU53.jpg" alt="enter image description here"></p> <p>What is the reason for interference at 4 MHz? Is there a limitation to maximal frequency on digital out? I do not really need it for some particular project, just wanted to know it.</p> <p>I've asked this question on <a href="https://stackoverflow.com/questions/30201318/disturbed-digital-out-at-4mhz-on-arduino-nano">stackoverflow</a>, but then I've discovered this dedicated forum so... I've decided to try it out ;)</p>
<p>Thank you - correct trigger solves my problem: <img src="https://i.stack.imgur.com/VFWpu.jpg" alt="enter image description here"></p>
11824
|hardware|
Difference between Arduino.cc and Arduino.org
2015-05-14T11:10:23.023
<p>Recently I have noticed that there are two arduino sites, arduino.cc and arduino.org. They both have the Arduino logo and both sell what seems to be official Arduino boards. Also, arduino.org came out with the Arduino Zero board first. What is the deal here? Has Arduino partnered with another site? Any ideas appreciated.</p>
<p>Update on the situation: on October 1st, 2016 a blog post at arduino.cc "<a href="https://blog.arduino.cc/2016/10/01/two-arduinos-become-one-2/" rel="noreferrer">Two Arduinos become one</a>" announced that an agreement was found between arduino.cc and arduino.org. Two key points: </p> <ul> <li>the creation of a foundation </li> <li>the creation of a holding.</li> </ul> <p>About the holding:</p> <blockquote> <p>At the end of 2016, the newly created “Arduino Holding” will become the single point of contact for the wholesale distribution of all current and future products, and will continue to bring tremendous innovations to the market.</p> </blockquote> <p>About the foundation:</p> <blockquote> <p>In addition, Arduino will form a not-for-profit “Arduino Foundation” responsible for maintaining the open-source Arduino desktop IDE, and continuing to foster the open-source movement by providing support for a variety of scholarships, community and developer initiatives.</p> </blockquote>
11840
|arduino-uno|servo|
Arduino SoftwareServo by example
2015-05-14T15:04:15.743
<p>I am interested in writing a simple Arduino program that will turn a servo back and forth (180 degrees each time) continuously.</p> <p>I am looking at <a href="http://rads.stackoverflow.com/amzn/click/B00KA393PK" rel="nofollow">these servos</a> and am planning on following <a href="http://playground.arduino.cc/ComponentLib/servo" rel="nofollow">this example</a>.</p> <p>Being so new to Arduino, I first wanted to confirm that the <code>SoftwareServo</code> library in that example will drive those particular servos. If it will not, then can someone begin by explaining to me <em>why</em> these servos are incompatible with the lib?</p> <p>Assuming they are compatible, I am looking at the main example on that page (comments stripped out for brevity):</p> <pre><code>#include &lt;SoftwareServo.h&gt; SoftwareServo myservo; int potpin = 0; int val; void setup() { myservo.attach(2); } void loop() { val = analogRead(potpin); val = map(val, 0, 1023, 0, 179); myservo.write(val); delay(15); SoftwareServo::refresh(); } </code></pre> <p>My concerns:</p> <ul> <li>There seem to be 3 pins involved here: a potentiometer pin (<code>0</code>), an analog pin (<code>val</code>) and a servo pin (<code>2</code>). What is the purpose of each of these pins, and is this 3-pin wiring common across all/most servos?</li> <li>Is there anything "wrong" with defining <code>myservo.attach(2);</code> up <em>above</em> the <code>setup</code> function, and leave the <code>setup</code> function an empty no-op function?</li> <li>Where does the <code>map(...)</code> function come from? If it was defined inside <code>SoftwareServo</code> I would have expected its usage to be something like <code>SoftwareServo::map(...)</code>, etc.</li> <li>Why do we need the <code>delay</code> after calling <code>myservo.write(val);</code>? What would happen if this delay wasn't in there?</li> <li>According to that link, calling <code>SoftwareServo::refresh()</code> once every 50ms is necessary in order to: "<em>keep your servos updating.</em>" <strong>But what does this mean, really?</strong> Updating to what?!?</li> </ul>
<p>1- there is only two pins a servo pin which is D2 and an analog pin which is A0. D2 pin for writing analog value to servo. D2 pin is used for getting analog pin value. </p> <p>2- map function is a default function like sin, cos or digitalRead so library inport not necesary.</p> <p>3- delay function and waiting 50ms is used to wait servo response time. if you change servo angle too quickly servo will not respond accurately </p>
11846
|eeprom|
Is EEPROM persisted across program flashes?
2015-05-14T16:57:34.770
<p>If I use <code>EEPROM.write(someAddr, someValue)</code> to write a value to an address, how long will that value "stick" to that address before being lost?</p> <p>If I were to power down the Arduino, flash a whole new program to it, and power it on, could I still retrieve that old/cached value written from the previous program?</p>
<blockquote> <p>how long will that value "stick" to that address before being lost?</p> </blockquote> <p>The Atmega328 data retention is guaranteed by Atmel (the manufacturer) for 20 years at 85 degrees Celsius, 100 years at 25 degrees Celsius. Beware cheap Chinese clones usually use counterfeits chips, meaning those values are not going to be guaranteed any more</p> <blockquote> <p>If I were to power down the Arduino, flash a whole new program to it, and power it on, could I still retrieve that old/cached value written from the previous program?</p> </blockquote> <p>While @ignacio answer is more detailed I believe you are interested in plain Arduino IDE programming along with standard Arduino boards, in which case the answer is <strong>yes</strong>, the data is not going to be erased.</p>
11860
|arduino-due|performance|
Help needed understanding Due performance
2015-05-15T07:56:38.607
<p>I'm going to be writing some performance critical code and have started trying to get an understanding of timers and how much "work" the Due CPU can do per second. To help get started with this, I wrote a bare sketch that simply increments a counter whilst a timer which ticks every second dumps the value of the counter to the serial log and then resets the counter. Here's the code I'm using:</p> <pre><code>#include &lt;Arduino.h&gt; void EnableTimer7TickEverySecond(); volatile uint32_t gCounter = 0; void setup() { Serial.begin(9600); EnableTimer7TickEverySecond(); // while ( true ) // { // ++gCounter; // } } void loop() { ++gCounter; } void EnableTimer7TickEverySecond() { pmc_set_writeprotect(false); pmc_enable_periph_clk(ID_TC7); TC_Configure(TC2, 1, TC_CMR_WAVE | TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK1); TC_SetRC(TC2, 1, 656000 * 64); TC_Start(TC2, 1); TC2-&gt;TC_CHANNEL[1].TC_IER = TC_IER_CPCS; TC2-&gt;TC_CHANNEL[1].TC_IDR = ~TC_IER_CPCS; NVIC_EnableIRQ(TC7_IRQn); } void TC7_Handler() { TC_GetStatus( TC2, 1 ); Serial.println( (uint32_t)gCounter ); gCounter = 0; } </code></pre> <p>When I run this, I get values averaging 446,000 in the serial log for the increments per second. That is way lower than I was expecting. On an ARM chip running at 84MHz, I'd expect at least 14 million increments as few ARM instructions take more than 2 clock cycles and an increment should involve a read from memory, addition and a write back to memory (approx 6 clock cycles by my reckoning).</p> <p>The timer is configured correctly, the TX led flashes regularly at 1 second intervals as the Serial.println is called. I've checked for overflow on the counter (oddly, I found that the number of increments when working with a uint64_t was slightly higher). I've also tried not calling Serial.begin() until I'm about to write the value to the log (and then only writing the value once) and whilst there is a slight increase in "performance", it doesn't account for the whole difference between expectation and reality.</p> <p>My best guess would be that loop() is called on some sort of timer or has a built in default delay, so it occurred to me that if I comment out the counter increment in loop() and instead comment in the infinite while loop in setup(), I should be able to counteract any delay caused by how frequently the Arduino IDE calls loop(). I have seen other examples that never bother with loop() and just stick all their code in setup().</p> <p>I do see a performance increase with this setup, but only to around 9 million, not the 14+ million I would expect. Oddly though, sometimes, randomly, the value is 2 or 3 times the "usual" value. Not between 2 and 3 times, but exactly 2 or 3 times. This happens regardless of whether I am incrementing the counter inside the loop() function or my own loop inside setup(). It is not a case of the timer "skipping", the output is written every second like clockwork.</p> <p>So, my questions are:</p> <ul> <li><p>What does the Arduino library do to make loop() so inefficient?</p></li> <li><p>Is there any harm in keeping all your code inside an infinite loop in setup() and never returning out of it?</p></li> <li><p>Why would I sometimes see the number of increments being 2 or 3 times higher than usual? Could the counter be getting cached (despite being marked as volatile) and not reset properly? If so, how can I prevent this?</p></li> </ul>
<blockquote> <p>What does the Arduino library do to make loop() so inefficient?</p> </blockquote> <p>Alot. For a start it's a function, so it has to push registers onto the stack before it runs, and pop them off afterwards. Secondly there is the "serial event" system outside the loop. In main.cpp in the core you can see how loop is called:</p> <pre><code>setup(); for (;;) { loop(); if (serialEventRun) serialEventRun(); } </code></pre> <blockquote> <p>Is there any harm in keeping all your code inside an infinite loop in setup() and never returning out of it?</p> </blockquote> <p>If you don't use serial events, no harm whatsoever.</p> <blockquote> <p>Why would I sometimes see the number of increments being 2 or 3 times higher than usual? Could the counter be getting cached (despite being marked as volatile) and not reset properly? If so, how can I prevent this?</p> </blockquote> <p>My guess is the operations you are using are not atomic. This is, the interrupt is able to be fired right in the middle of doing the series of instructions that perform the increment. The temporary registers end up not being the same as they were at the start of the operation, and consequently the value is corrupted. You should wrap the increment in a <em>critical section</em> (i.e., disable interrupts before it, and enable them afterwards).</p> <p>To better analyse the speed of execution you can look at the generated assembly code of your program. If we look at the disassembled <code>main()</code> function for the bit where it loops you can get this:</p> <pre><code>80596: f7ff fe05 bl 801a4 &lt;loop&gt; 8059a: 4b04 ldr r3, [pc, #16] ; (805ac &lt;main+0x30&gt;) 8059c: 2b00 cmp r3, #0 8059e: d0fa beq.n 80596 &lt;main+0x1a&gt; 805a0: f7ff feec bl 8037c &lt;_Z14serialEventRunv&gt; 805a4: e7f7 b.n 80596 &lt;main+0x1a&gt; 805a6: bf00 nop </code></pre> <p><code>loop()</code> consists of this:</p> <pre><code>801a4: 4b02 ldr r3, [pc, #8] ; (801b0 &lt;loop+0xc&gt;) 801a6: 681a ldr r2, [r3, #0] 801a8: 3201 adds r2, #1 801aa: 601a str r2, [r3, #0] 801ac: 4770 bx lr 801ae: bf00 nop </code></pre> <p>If we feed that into <code>main()</code> where it calls <code>loop()</code> the finished code looks like:</p> <pre><code>80596: f7ff fe05 bl 801a4 &lt;loop&gt; 801a4: 4b02 ldr r3, [pc, #8] ; (801b0 &lt;loop+0xc&gt;) 801a6: 681a ldr r2, [r3, #0] 801a8: 3201 adds r2, #1 801aa: 601a str r2, [r3, #0] 801ac: 4770 bx lr 801ae: bf00 nop 8059a: 4b04 ldr r3, [pc, #16] ; (805ac &lt;main+0x30&gt;) 8059c: 2b00 cmp r3, #0 8059e: d0fa beq.n 80596 &lt;main+0x1a&gt; 805a0: f7ff feec bl 8037c &lt;_Z14serialEventRunv&gt; 805a4: e7f7 b.n 80596 &lt;main+0x1a&gt; 805a6: bf00 nop </code></pre> <p>So that is what gets executed for every single iteration of <code>loop()</code>. If we (incorrectly) assume that each instruction takes 1 clock tick, that's 13 ticks. 84,000,000 / 13 = ~6.4 million loops per second.</p> <p>Now - if we map the instructions against actually how many clock cycles they take, we can get a clearer picture:</p> <pre><code>bl 1+P (P = 1 to 3) ldr (pc relative) 2 ldr (word) 2 adds 1 str (word) 2 bx 1+P (P = 1 to 3) nop 1 ldr (pc relative) 2 cmp 1 beq.n 1 or 1+P (P = 1 to 3) bl 1+P (Only if serial event runs) b.n 1 or 1+P (P = 1 to 3) nop 1 </code></pre> <p>So taking a worst case scenario where P = 3 (pipeline re-fill clock counts, that is), and no serial event running, we can calculate a total number of clock cycles of 4+2+2+1+2+4+1+2+1+4+0+4+1 = 28.</p> <p>84,000,000 / 28 = 3,000,000 loops per second.</p> <p>But hang on - that's still much more than you're seeing. That's because you're still only looking at the small picture. You're looking at just your sketch and forgetting what else there is going on.</p> <p>Every millisecond the <code>SysTick_Handler()</code> gets called which does various tasks, including calling the <code>TimeTick_Increment()</code> routine to deal with <code>millis()</code>. That's 1,000 times per second, and that eats into your processing time somewhat.</p> <p>Another important point is <em>it can't be incrementing while you're running your interrupt</em>. The more you do in your interrupt (<em>and using serial is a very heavy-weight thing to do in an interrupt</em>) the less of your 1-second slice you get for doing your incrementing.</p> <p>As an experiment, why not try disabling all the interrupts except just the one you are using for your timer and see how it changes the value.</p>
11874
|arduino-uno|programming|gsm|electronics|
How to power on Arduino a few seconds later after GSM module initialization?
2015-05-15T17:47:18.330
<p>I've connected a SIM900A GSM module to Arduino and the circuit works standalone on a 12V power supply. The problem is when I provide the 12V power supply, both GSM module and Arduino starts but the Arduino don't initializes the program for GSM module and hence the send or receive message functions don't work. Also when I first power on the GSM module and let it initialize first and then power on the Arduino, everything works fine. How to deal with this problem? </p>
<p>It sounds like your problem is that the GSM module needs time to initialize before it is ready to be talked to by the Arduino.</p> <p>A crude way of providing this would be to use the <code>delay()</code> function in the Setup() of your sketch. The argument to that is an <code>unsigned long</code> number of milliseconds (thousandths of a second) so it can produce delays far longer than you need.</p> <p>But a more sophisticated solution would be to repeatedly try to talk to the module and check for an expected response. Apparently, with at least some of these, if you disable baud rate detection they will announce themselves with a prompt when they are ready - you could wait for that. But I think repeatedly trying until you get a response is going to be the most robust.</p>
11885
|serial|power|usb|
Is supplying 5V from both external 5V and USB harmful?
2015-05-16T07:18:44.290
<p>I have an arduino nano which is powered through unregulated 5V (pin 27). For debugging purpose, I'd like to connect the USB port to my computer in order to use the Serial.Print function. The external 5V will stay connected. Will this cause damage ?</p> <p>edit : I forgot to mention that the external power supplied to pin 27 is regulated with a switching DC-DC converter (measured 5.1V). Sorry it was not clear in my question.</p> <p>Here is my circuit : </p> <p><img src="https://i.stack.imgur.com/avlw4.png" alt="Schema"></p> <p>The switching regulator is not exactly the one in the schema.</p> <p>Is using the circuit with the battery power supply + usb connection to my computer will damage something ?</p>
<p>No, it probably won't damage anything, as the PC's USB port is protected from overvoltage by the D1 schottky device on your arduino board.</p> <p><strong>Update, my previous answer contained the following paragraph, which is not related to your problem</strong></p> <blockquote> <p>But you should take care of some things. </p> <ol> <li>Make sure, the voltage applied to your +5V-Net is regulated properly elsewhere. I.e. choose a laboratory PSU or another good source. </li> <li>Avoid having both your PC and your 5V-supply connected to line voltage. Ground levels may differ due to Y-capacitors present in the switching PSUs. Those provide a AC voltage of half your line voltage to DC ground (only with 0.3 to 0.7 mA, but enough to cause disturbances on your signals at 55 volts in the US or 115 V in the EU)</li> <li>If you have to use two switching PSU for both PC and arduino, provide an equipotential bonding between your PC's mass (e.g. VGA-port-screw) to your arduino's PSU's ground directly, to prevent leakage currents from the Y-capacitors wandering around in your circuitry.</li> </ol> </blockquote> <p><strong>Update according to your enhanced question</strong></p> <p>You are using a battery powered DC-DC supply for your Arduino. So, my previous notes do not apply to your problem. </p> <ul> <li>5.1 V seem exact enough to drive your arduino safely. No need for additional stabilisation measures</li> <li>D1 (see genuine arduino schematic) separates USB-Power from +5V and prevents current flowing in reverse direction over your USB connection.</li> <li>Arduino circuitry and USB port have common GND so there are always well defined voltage levels.</li> </ul> <p>In my opinion, there's nothing with your setup, which may harm your circuitry or your PC.</p> <p>Depending on the maximum power of your DC-DC converter you may consider adding a fuse to protect converter and components in case of short circuit.</p>
11896
|arduino-uno|esp8266|ftdi|
Simulate a FTDI using an Arduino UNO
2015-05-16T18:55:31.917
<p>I'm looking to directly program an ESP8266 WiFi Module with out using a FTDI (USB-Serial interface) as suggested in this excelent <a href="https://www.openhomeautomation.net/control-a-lamp-remotely-using-the-esp8266-wifi-chip/" rel="nofollow">tutorial</a>. The real purpose is to have access to the GPIO ports of the module.</p> <p>I heard (from <a href="http://hackaday.com/2009/09/22/introduction-to-ftdi-bitbang-mode/" rel="nofollow">this page</a>) that one can use an Arduino UNO as an intermediate interface for burning the bootloader onto an AVR (e.g. ATmega168 or ATmega328). That is, using the ArduinoISP code example in the IDE.</p> <p>Is it possible to use an Arduino UNO as temporal bridge to program the ESP8266? Can anyone please suggest some tutorial? Thanks</p>
<p>The simplest way is to unplug the ATMega328P from the board (or otherwise disable it) and just use the ATMega16U2 by connecting the ESP8266 to pins 0 and 1 of the Uno. No programming required at all then - the ESP8266 just takes the place of the ATMega328P.</p> <p>If you really want to "pass it through" the ATMega328P then you will need to make a transparent pipe for the serial data. That would involve nominating two more pins on the Uno to be a new serial connection, and using SoftwareSerial to interface with those pins. Then you have a simple loop which reads from one port and writes to the other, and the same in reverse of course. Make sure you have the baud rates right. I don't know how well SoftwareSerial would perform at the (commonly) 115200 baud the ESP8266 works at.</p> <p>EDIT: (Interfacing to a 3.3-V system) </p> <p>Since the ESP8266 works at 3.3V, while the ATMEGA16U2 is powered at 5V, you might need to adapt the level of the ATMEGA16U2's TXD line (which is connected to the "RX" input line of the ATMEGA328P/Arduino Uno Board), to 3.3V.</p> <p>To do this, connect a 1.5 kOhm resistor between the RX pin and ground. In fact, the connection between ATMEGA16U2 and ATMEGA328P is done using an 1kOhm series resistor. This, together with the 1.5k Ohm resistor, will create a resistor divider, which converts the 5V output to 3V.</p> <p>See schematics below. <a href="https://i.stack.imgur.com/XVPNz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XVPNz.png" alt="Suggested modifications"></a></p>
11907
|sensors|
How do I even out Infared distance sensor readings?
2015-05-16T23:32:13.663
<p>I am using a standard infared distance sensor on a small robot and i am trying to even out the readings on it so it is more accurate. The readings are very sporadic and often take huge jumps in the distance. Is there a method of programming or circuit design that might make this easier to use? I'm trying to keep my robot from running into things. </p>
<p>The Sharp GP... infra red proximity sensors can produce noisy output sometimes. This is partly caused by the fact that they work by repeating a brief, powerful IR pulse.</p> <p>So - the very first tweak I would suggest when using any of these sensors is to try a cheap 10 micro Farad electrolytic capacitor on the 5V power connections, reasonably close to the sensor itself. This is mentioned on some of their datasheets, but gets forgotten...</p>
11915
|power|
Is it safe to feed 5v dc 1amp to an Arduino uno R3 board?
2015-05-17T09:09:11.040
<p>Is it safe to feed 5v dc 1amp to an Arduino uno board?</p>
<p>That's a common newbie question: "What will happen when I use a 1 A power supply for a device which only needs 0.1 A?"</p> <p>The device will only draw the current it needs. It's the same as on your electricity grid. The nuclear power plant can supply a gigawatt, yet the bulb will only draw the 60 W it needs.</p> <p>But do you want to apply that 5 V to the power connector? Then the 5 V is too low, you'll need at least something like 6.5 V, otherwise the onboard voltage regulator won't have enough headroom to output 5 V. If you're using the USB connector for a <strong>regulated</strong>(!) 5 V, then the onboard regulator will be bypassed. Never place an unregulated 5 V on the USB connector, though.</p>
11928
|arduino-uno|led|pwm|
How to fade in and fade out led strip connected to arduino based on continous analog input from capacitative sensor?
2015-05-17T14:31:13.390
<p>So I've been trying to get a capacitive sensor made from aluminum foil to work. And I have had success the kind of proximity and readings I need to light up a single LED and produce basic tone. Using this very basic code : </p> <pre><code>{ Serial.println(value1);//value that i get from analog sensor //this is just to get the values in order for the led and sound if (value1&lt;=8) value1=-100; analogWrite(ledPin,value1+100);//these weird calculations seem to work for me tone(tonepin,value1+100,100); delay(10); </code></pre> <p>All this works perfectly for me, the delay isn't perceivable, the response is for all practical purposes simultaneous to input. Except it's not beautiful, because the LED keeps flickering when values reduce or increase because the jumps are sudden I suppose. </p> <p>SO I thought I'll try to fade in and fade out to different values from present values. Used the fading examples. Here:</p> <pre><code>Serial.println(value1); if (value1&lt;=8) value1=-100; if (value1+100&lt;=value2+100) { for(int fadeValue = value2+100 ; fadeValue &lt;= value1+100; fadeValue +=5) { analogWrite(ledPin, fadeValue); delay(10); } } else { for(int fadeValue = value2+100 ; fadeValue &gt;= value1+100; fadeValue -=5) { analogWrite(ledPin, fadeValue); delay(10); } } //analogWrite(ledPin,value1+100); tone(tonepin,value1+100,100); delay(10); value2=value1; </code></pre> <p>But this takes away the responsiveness, the whole thing is so slow to react, the sound and the light are obviously not in sync as I read my code. But also the light is not really fading, still blinking, but there seems to be some effect but I am not sure. </p> <p>Any help with what I could do and what I am doing wrong would be nice. </p>
<p>You need to re-think the entire way of dealing with the fading.</p> <p>Instead of saying "The value has changed, fade the LED to that brightness", you need to say "The value has changed. I want the LED to be this brightness." followed by "Is the LED the brightness I want? No? Then move it a bit towards the brightness I want".</p> <p>Something like, in pseudo-code:</p> <pre><code>TargetBrightness = SensorValue if LEDBrightness &lt; TargetBrightness increment LEDBrightness set LED to LEDBrightness if LEDBrightness &gt; TargetBrightness decrement LEDBrightness set LED to LEDBrightness </code></pre> <p>If that all happens too fast then you need to only run the brightness tests at certain periods. Something like:</p> <pre><code>TargetBrightness = SensorValue Has 10ms passed since last check? Yes? Remember the time this check happened. if LEDBrightness &lt; TargetBrightness increment LEDBrightness set LED to LEDBrightness if LEDBrightness &gt; TargetBrightness decrement LEDBrightness set LED to LEDBrightness </code></pre>
11944
|hardware|
Arduino Tre, will it ever come out?
2015-05-17T22:26:43.547
<p>Does anyone have any information other than "coming soon" about the Tre?</p> <p><ul><li>Could the Tre be stuck in development hell?</li> <li>Perhaps the new partnership with Adafruit could expidite things, seeing as Ardiuno (.cc) was touting the Tre to be the first Arduino made in the USA? </li> </ul><p>I'm just giddily awaiting its arrival, so I'm just wondering!</p></p>
<p>The latest news from Arduino that I can find is in their blog archive that the <a href="http://blog.arduino.cc/2014/12/12/arduino-tre-developer-edition-2nd-round-of-beta-testing/" rel="nofollow">second round of beta testing is out</a>.</p> <p>The mentioned this:</p> <blockquote> <p>When is the Arduino TRE going to be finally on the market? The board is ready, but we don’t have a final release date yet because we are still figuring out some manufacturing matters. We’ll keep you posted!</p> </blockquote> <p>I'd imagine that the <a href="http://hackaday.com/2015/02/25/arduino-v-arduino/" rel="nofollow">Arduino LLC vs Arduino SLR</a> legal issue is also delaying the production.</p> <p>Other than that, speculation is all that we know.</p> <p>P.S: it's still spring until Sunday, June 21! :-)</p>
11946
|arduino-uno|serial|sensors|
How to get weight data from glass electronic bathroom scale sensors?
2015-05-17T22:56:13.453
<p>I am doing a small project with a bathroom scale but I run into some problems. I am using an Arduino Uno V3, HX711 module amp and a scale. </p> <p>Scale: <img src="https://i.stack.imgur.com/Bxnr9.jpg" alt="Digital bathroom scale with 4 sensors"></p> <p>HX711 amplifier: <img src="https://i.stack.imgur.com/NppEm.jpg" alt="Amplifier"></p> <p>I disassembled the scale to get to sensor wires and I am a bit confused. These sensors have three wires each. So they are half bridge sensors. The scale is using 4 sensors so when the scale is measuring it is measuring with a full bridge. And these 3 wires are RED, BLACK, BLUE. I don't know what is black (GND or Positive) and blue (same guess). Four red wires are given names E+, E-, S+ and S-. I will provide a picture of the disassembled scale. <img src="https://i.stack.imgur.com/04AzD.jpg" alt="Sensor wires"></p> <p>Two blue wires are soldered together on each side. I guess red wires are signal (S+, S-, E+ and E-) but what are Blue and Black? Then I soldered the wires to these wires to get sensor readings but I don't know what is what. <img src="https://i.stack.imgur.com/en6bG.jpg" alt="Config"></p> <p>The sensor is looking like this: <img src="https://i.stack.imgur.com/EGMol.jpg" alt="enter image description here"></p> <p><strong>I tried:</strong></p> <ol> <li>Two different libraries for this project both named HX711 (for this module)</li> <li>Changing A+ for A- on module</li> </ol> <blockquote> <pre><code>// Hx711.DOUT - pin #A1 // Hx711.SCK - pin #A0 #include "hx711.h" Hx711 scale(A1, A0); void setup() { Serial.begin(9600); } void loop() { Serial.print(scale.getGram(), 1); Serial.println(" g"); delay(200); } </code></pre> </blockquote> <p>with no success. I get 0.0g on the serial monitor when calm, and the same when load is on.</p> <p><strong>My questions are:</strong> How to know which wire is GND, +5V and which is signal? How to connect 4 of these sensors to read data? How to use HX711 libraries available and HX711 module? And, most important, how to read data from this scale on serial?</p>
<p>Your four half bridge load cell sensors can connect into a full wheatstone bridge as in <a href="https://electronics.stackexchange.com/a/199470/30711">https://electronics.stackexchange.com/a/199470/30711</a> </p> <p>If your sensors are like this 50kg load cell from SparkFun's <a href="https://www.sparkfun.com/products/10245" rel="noreferrer">https://www.sparkfun.com/products/10245</a> or Ebay's <a href="http://www.ebay.com/itm/4pcs-Body-Load-Scale-Weighing-Sensor-Resistance-Strain-Half-bridge-Sensors-50kg-/251873576571" rel="noreferrer">http://www.ebay.com/itm/4pcs-Body-Load-Scale-Weighing-Sensor-Resistance-Strain-Half-bridge-Sensors-50kg-/251873576571</a> they might have a compression and tension gage both on the top surface. The Ebay site has a diagram like:</p> <p><a href="https://i.stack.imgur.com/PrHOR.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/PrHOR.jpg" alt="three-wire 50kg load cell"></a> ... which indicates a positive strain gauge on the red-white, and a negative strain on the red-black. (note that the coloring order in this diagram does not match the coloring order in this picture. I have a similar gauge with blue-red-black colors, and the positive strain gauge is the right pair, negative on the left.) The gauged surface on the center bar between the face-to-face coupled 'E's in the sensor should act like a parallel bar and has portions under compression and under tension, rather than purely under tension. In cross-section, the gauged bar in the center is sort of the cross-piece in a Z-shaped spring. In this case, the strains oppose each other, and, if manufactured well, the reduction of resistance in the negative strain portion will offset the increase in resistance in the positive strain portion and the total white-black resistance should be constant. One still needs to set up the bridge so that the voltage dividers move in opposite directions with added load, and 4 devices wired in a white-to-white and black-to-black loop should work as above. </p> <p>If you wire four of these up carefully by flipping them around so the stress sensitive portions unbalance the bridge constructively, you can use all four sensors without any extra resistors. </p> <p>Basically, two diagonally-opposite sides of a wheatstone bridge are each formed by the compression elements of two gauges wired in series, while the remaining two sides of the bridge are each formed from two tension elements from two cells. With load on all the sensors, the compression resistances are reduced, while the tension resistances are increased and it pulls the bridge out of balance.</p> <p>To get this, wire all four sensors in a big ring with maximum resistance, matching colors and initially ignoring the red center tap wires. (This is the function of the soldered-together blues and blacks are in your scale.) Choose two opposite (red) center taps as E+ and E-, and the remaining two (red) center taps as S+,S-. Put the excitation voltage on the E+/E- from the diagram above and read a force-sensitive voltage difference across S+/S-, and this is what you feed into your HX711 as A+ and A- (Ignore B+/B- as a second, unused channel.)</p> <p>Here's a schematic with gauges 1-4 as G1 G2, G3, G4 per the above specs, applying an excitation on the G1 and G3 reds, and reading the signals off the G2 and G4 reds. The G4 gauge is loaded a bit with some positive strain increasing the G4+ resistance, and some negative strain reducing the G4- resistance. Ideally, loading G4 with 25kg would produce 0.5mV/V times its 2.5V excitation voltage, producing 1.250mV across Sig+/Sig-, and stretching R8 to be 1001 ohms and compressing R7 to 999 ohms as shown. (The schematic/simulator thing on electronics.stackexchange.com is pretty cool.)</p> <p><img src="https://i.stack.imgur.com/GYEy2.png" alt="schematic"></p> <p><sup><a href="/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fGYEy2.png">simulate this circuit</a> &ndash; Schematic created using <a href="https://www.circuitlab.com/" rel="noreferrer">CircuitLab</a></sup></p> <p>Instead of the "White" wires in the diagram and like on my gauges, consider it the "blue" wires from your scale's sensors.</p> <p>With only two of these half-bridge sensors, one should not match the end colors and hook white-to-black (blue-to-black) and black-to white, (black-to-blue) imposing an excitation voltage from between these two junctions, and read the differences across the reds, as increased load pulls one side high and the other side low. This will look like the plain 4-resistor wheatstone bridges in the common datasheets, rather than the 4-half-bridge/eight-resistor scheme above. </p>