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
16756
|arduino-ide|
How come the console prints error `avrdude: usbdev_open(): did not find any USB device "usb"`?
2015-10-12T08:14:11.080
<p>How come when I try to push a sketch to my Arduino I see this error on the console? The subsequent sketch does not work.</p> <blockquote> <p>avrdude: usbdev_open(): did not find any USB device "usb"</p> </blockquote> <p>I've already added myself to the <code>dialout</code> group,</p> <blockquote> <p>sudo usermod -aG dialout $USER</p> </blockquote> <p>And, I did that after I confirmed the <code>dialout</code> group owns the device (in my case <code>/dev/ttyACM0</code>:</p> <pre><code>$ ls /dev/ttyACM0 -l crw-rw---- 1 root dialout 166, 0 Oct 12 03:15 /dev/ttyACM0 </code></pre>
<p>Try "Tools> Port:> then select your board" Make sure your pc hasn't assigned new com port to the attached usb (Arduino) </p>
16765
|float|byte-order|
How to cast float into four bytes?
2015-10-12T15:16:24.813
<p>I'm trying to save GPS coordinates to an EEPROM.</p> <p>In this example I feed it the latitude of 56060066 as the argument float x</p> <pre><code>void writeFloat(unsigned int addr, float x) { byte seriesOfBytes[3]; *((float *)seriesOfBytes) = x; // Write all four bytes. for(int i = 0; i &lt; 4; i++) { i2c_eeprom_write_byte(0x57, addr, myFloat.bytes[i]); // Write byte to EEPROM Serial.println(seriesOfBytes[i],BIN); // Debug line } } </code></pre> <p>I'm expecting to receive the following four bytes from the serial print:</p> <pre><code>00000011 01010111 01101000 10100010 </code></pre> <p>Instead I'm getting these:</p> <pre><code>00101000 11011010 01010101 01001100 </code></pre> <p>I've tried changing all sorts of parameters, but can't seem to find the problem. Can anyone spot the issue?</p>
<pre><code>union Float { float m_float; uint8_t m_bytes[sizeof(float)]; }; float pi,pi1; uint8_t bytes[sizeof(float)]; uint8_t bytes1[sizeof(float)]; Float myFloat; #include &lt;Wire.h&gt; #define disk1 0x50 //Address of 24LC256 eeprom chip void setup(void) { unsigned int address = 0; Serial.begin(9600); Wire.begin(); pi = 300.78; Serial.println("*******************************************"); Serial.println("pi = "+ String(pi)); Serial.println("***** Conversion by using type casting *****"); *(float*)(bytes) = pi; for(int i=0;i&lt;4;i++) Serial.println( bytes[i]); Serial.println("*******************************************"); for( int i=0;i&lt;4;i++){ writeEEPROM(disk1, address, bytes[i]); address=address+sizeof(bytes[i]); } address=0; for( int i=0;i&lt;4;i++){ bytes1[i]=(readEEPROM(disk1, address)); address++; Serial.println(bytes1[i]); } Serial.println("************Conver Byte to Float*************************"); pi1 = *(float*)(bytes1); Serial.println("pi = "+String( pi1)); Serial.println("********* Conversion by using union *********"); myFloat.m_float = pi1; // assign a float to union Serial.println("myFloat.m_Float = "+String( myFloat.m_float)); Serial.println("myFloat.m_Bytes = "+String(myFloat.m_bytes[0])+String(myFloat.m_bytes[1])+String(myFloat.m_bytes[2])+String(myFloat.m_bytes[3])); // get the bytes } void loop(){} void writeEEPROM(int deviceaddress, unsigned int eeaddress, byte data ) { Wire.beginTransmission(deviceaddress); Wire.write((int)(eeaddress &gt;&gt; 8)); // MSB Wire.write((int)(eeaddress &amp; 0xFF)); // LSB Wire.send(data); Wire.write(data); Wire.endTransmission(); delay(5); } byte readEEPROM(int deviceaddress, unsigned int eeaddress ) { </code></pre>
16769
|arduino-uno|ubuntu|
How can program/arduino restarted by IDE?
2015-10-12T16:14:47.590
<p>I wrote my custom sketch, where I am printing some greeting text inside <code>setup()</code> method.</p> <p>I found, that each time I am restarting IDE, and opening serial monitor, a greeting text is printed there again, i.e. <code>setup()</code> method running again.</p> <p>How can this happen? I was thinking <code>setup()</code> method run once, when Arduino is powered up by connecting to the USB socket?</p> <p>If it is possible to restart it already connected, then how this can be done?</p> <p><strong>UPDATE</strong></p> <p>Code is follows:</p> <pre><code>#include &lt;Wire.h&gt; #include &lt;Adafruit_BMP085.h&gt; Adafruit_BMP085 bmp; String command; String awaitingMessage = "Temperature and pressure sensor awaiting commands\r\nCommand \'help\' is for help"; void awaiting() { Serial.println(awaitingMessage); } void help() { Serial.println("Temperature and pressure sensor commands:"); Serial.println("temp\t- output temperature in degrees Celsius"); Serial.println("press\t- output pressure in Pascals"); Serial.println("wait\t- print awaiting message"); Serial.println("help\t- output this text"); } void temperature() { Serial.println(bmp.readTemperature()); } void pressure() { Serial.println(bmp.readPressure()); } void unknown() { if( command.length() &gt; 0 ) { Serial.println("Unknown command was \'" + command + "'"); } } void setup() { Serial.setTimeout(50000); Serial.begin(9600); if (!bmp.begin()) { Serial.println("Could not find a valid BMP085 sensor, check wiring!"); while (1) {} } else { awaiting(); } } void loop() { command = Serial.readStringUntil('\n'); if( command.startsWith("temp") ) { temperature(); } else if( command.startsWith("press") ) { pressure(); } else if( command.startsWith("wait") ) { awaiting(); } else if( command.startsWith("help") ) { help(); } else { unknown(); //awaiting(); } } </code></pre> <p>Video is here: <a href="https://youtu.be/-QBleGVxaus" rel="nofollow">https://youtu.be/-QBleGVxaus</a></p>
<p>When you open the serial monitor (or even just go to the serial port menu) the serial port is opened. When the serial port is opened the DTR line is asserted. This is the method that the Arduino uses to reset so that you can access the bootloader and upload a new sketch.</p> <p>Every time you open the serial port - through whatever means you choose - you reset the board, whether you like it or not.</p> <p>There are a number of "fixes" for this - the simplest is to add a large (say 10µF) capacitor between the RESET and GND pins of the Arduino to filter out the reset pulse that would otherwise reboot the board.</p> <p>There are also ways of disabling the reset within Windows, but that requires you to write your own software to interface with the board instead of using the serial monitor.</p> <p>Some boards also come with a method of completely detaching the reset signal from the USB interface, but modifying the board itself isn't for beginners.</p> <p>Just remember that once you have disabled reset through whatever means you will have to re-enable it (resolder the track you cut, remove the capacitor, whatever) before you can upload a new sketch.</p>
16772
|serial|sensors|c++|interrupt|servo|
Servos and ultrasonic at the same time
2015-10-12T16:44:27.427
<p>So recently I started making a sonar out of ultrasonic HC-SR04 sensor and servo motor. The idea was to slowly rotate servo 180 degrees while measuring distance.</p> <p>Soon after I noticed that regular pulseIn() command could wait 20ms while doing nothing. So I started learning interrupts. I came up with a code which sends TRIG signal and records sending time with micros() function. When an interrupt occurs on ECHO pin, we subtract current time with TRIG time and get time of round trip of the sound. </p> <p>The code works as intended without servos connected, but it behaves interestingly ! I always get distance which is 8 cm bigger than actual distance. So I had to subtract 8 cm every time ! Also I noticed that max reliable range decreased , using pulseIn() I could measure distance of 400cm, and with mine code it starts to show weird numbers after 150cm...</p> <p>So i thought that 150cm is enough for me, and tried to run the code with servos attached. everything ran as intended, until the servos started to move. Now I was getting distance along with pretty much random numbers, periodically positive and negative.</p> <p>I could just use one the fancy libraries out there, but I am curious what am I doing wrong, why i need to subtract 8cm each time , why my reliable range decreased so much, and most importantly why am I getting weird values while servos are on ? </p> <p>CODE :</p> <pre><code>#include &lt;Servo.h&gt; #define ECHO 2 #define TRIG 7 Servo servo; int distance; volatile long echoTime = 0; long trigTime = 0,sendTime = 0,timeServo = 0; bool scanning = false; byte servoDir = -1,servoAngle = 0; void setup() { servo.attach(12); Serial.begin(115200); pinMode(ECHO,INPUT); pinMode(TRIG,OUTPUT); attachInterrupt(digitalPinToInterrupt(ECHO), echo_interupt, FALLING); } void loop() { // SERVO if((millis() - timeServo &gt; 10)){ if(servoAngle &lt;= 0 || servoAngle &gt;= 180)servoDir = -servoDir; servoAngle += servoDir; servo.write(servoAngle); timeServo = millis(); } // GETTING RESULTS if(echoTime &gt; 0){ distance = echoTime - trigTime; distance /= 58; echoTime = 0; trigTime = 0; Serial.println(distance - 8); } // SENDING PULSE if(millis() - sendTime &gt; 20){ digitalWrite(TRIG,LOW); delayMicroseconds(2); digitalWrite(TRIG,HIGH); delayMicroseconds(10); digitalWrite(TRIG,LOW); trigTime = micros(); sendTime = millis(); } } // INTERUPT void echo_interupt(){ echoTime = micros(); } </code></pre>
<p>I had problems with <code>Servo</code> library and <code>VirtualWire</code>. They both use the same internal timer. The solution was to change <code>Servo.h</code> to <code>ServoTimer2.h</code> lib.</p>
16774
|arduino-uno|pwm|
Can i run brushless ESC from any digital pin of arduino
2015-10-12T17:41:39.700
<p>{assume arming is done} Can i connect the brushless ESC to any digital pin and give writemicroseconds() to it? Will this work. because i have connected my 4 ESC's to "~" pins. so i thinks that other will not work.</p>
<p>It should work.</p> <p>The <a href="https://www.arduino.cc/en/Reference/Servo" rel="nofollow">Servo</a> library doesn't use hardware PWM, so you can connect them to a non "~" (PWM) pin.</p>
16790
|power|servo|battery|current|electronics|
Powering multiple servos on external battery
2015-10-12T22:37:50.553
<p>I am working on a project with my school's 3D Printing Club where we are making a humanoid robot and I am attempting to wire the arm at the moment, and program the hands to translate text to sign language. The portion of the arm I am currently working with uses six TowerPro 5010 servos, one for each finger, and another for the wrist, and I am controlling it with an Arduino Uno. I have a 9v wall plug that I am powering the Arduino with, and a 4xAA battery pack (wired in series for 6v, last measured at 5.7) that I would like to use for the servos.</p> <p>Initially, I wired the servo ground pins to the Arduino GND output, and the servo power pins to the battery pack's 6v output, I connected the ground on the battery to the ground on the Arduino, and I attached the servo motors to their IO pins. This approach worked perfectly for two servos, barely for three, and not at all for four. Even with most of the motors staying still (I was only moving one at a time with three and four servos, but I can move two simultaneously no problem with nothing else connected). Not sure how to describe the load on them quantitatively, but they are pulling on fishing line that has a good deal of resistance, but nothing excessive, or near their limits.</p> <p>I have been googling around for hours, and I found some tutorials where a similar battery was powering eight servos at a time, and so I am unsure why mine was cutting out so soon.</p> <p>I tried to reduce the load of the servos, but nothing I tried worked. At one point I tried wiring the servos on a shift register to only power the ones I needed, but then I realized this was a dumb idea because my shift register would never be able to output enough current to power even one servo. I have some 5v voltage regulators, but I don't think they will help since the servo takes from 4v to 6v, and I looked through all my transistors, but they are all designed for very small currents. I have a relay which should be able to switch that voltage that voltage easily, but only one of them. If possible I would like to try and do this without purchasing any additional components such as motor controllers or specialized batteries, but I understand that if I need to I need to. </p> <p>If anyone has any advice on how to proceed I would greatly appreciate it. Thanks.</p>
<p>If you dont mind to use a bit of space for a dedicated board that controls your servo and power them, I would suggest to use <a href="http://www.adafruit.com/product/815" rel="nofollow">http://www.adafruit.com/product/815</a> which is very good.</p> <p>Your issue might become a power draining where the batteries cant keep up to give enough amper to use 3 or 4 servos at the same time.</p> <p>I am not sure what kind of batteries you are using, probably not rechargeable ones but I would suggest to get an ampermeter to get the real draining on your circuit.</p> <p>After that you will understand a bit better what is going on and why this issue is happening on your configuration.</p> <p>I cant find the power consummation of this servo so I Cant give much more information.</p>
16793
|arduino-uno|sensors|robotics|
What type of sensor could I use to determine the mass of a small object (under 1 kg)?
2015-10-12T23:56:44.543
<p>I'm building a robot that needs to pick up a piece of material and then determine its mass. My robot will retrieve the material using a scoop at the ended of a mechanized arm. Once the material is in the scoop, the arm will tilt upwards until the material slides down the arm and into the chassis. I hope to weigh the material while its in the chassis, but I'm not sure how to do this. I've found that load sensors are useful for taking masses, but I'm not clear on how they're implemented. For example, I've found load beam cells, but how would I implement one in my design? Does it require a metal plate of some sort (like a weighing pan) on top of it like a laboratory scale? The sensor must be able to communicate with an Arduino.</p> <p>My robot needs to be under 6 lbs and have a footprint of 35 x 35 cm. Thanks!</p>
<p>A load beam cell would be good. Put it as one leg of your robot, and calibrate it with the arm in a particular location dangling over the cell. You'd need the beam load cell, and an instrumentation op amp, or HX711 (<a href="https://learn.sparkfun.com/tutorials/load-cell-amplifier-hx711-breakout-hookup-guide" rel="nofollow noreferrer">https://learn.sparkfun.com/tutorials/load-cell-amplifier-hx711-breakout-hookup-guide</a>) to do the interfacing.</p> <p>Also good would be the cells from a bathroom scale as the four feet -- you could hook them up like <a href="https://electronics.stackexchange.com/a/199907/30711">https://electronics.stackexchange.com/a/199907/30711</a> or <a href="https://electronics.stackexchange.com/a/199470/30711">https://electronics.stackexchange.com/a/199470/30711</a></p> <p>One thing cool about using the robot feet for measurement is that you could calibrate for more sensitive measurements while reaching far from the base, and rougher measurements closer. You could also calculate how far you could reach without toppling over.</p>
16805
|eeprom|
Most efficient way to store number in EEPROM?
2015-10-13T14:58:15.383
<p>I would like to store temperature readings in eeprom, the value from -55.00 to 125.99. What is the most space efficient way to store these numbers with two significant digits along with epoch timestamp?</p> <p>Thanks</p>
<p>My best off-the-top-of-my-head figure is 6 bytes.</p> <p>4 bytes for the timestamp (assuming a 32-bit value). Two byte for -32768 to +32767.</p> <p>Multiply the temperature by 100 to make it into the integer range -5500 to +12599. That then fits comfortably inside a 16-bit signed integer.</p> <p><em>However</em>, there are other tricks you can use.</p> <p>For instance, if you know the time of one reading you don't need to store the time of the next - only how much later it is. One byte can then store up to 255 "whatevers" later than the previous entry - be that seconds, minutes, hours, whatever.</p> <p>Similar with the temperature. You can just store the difference from the previous reading as a single byte if you know that successive readings will never deviate by more than +/-1.27 degrees.</p> <p>Also, you can check to see what the last saved temperature was, and only save a new temperature if it has changed from before.</p> <p>Another thing is the resolution of your data. You say 2 decimal points, but if the values are all multiples of 0.05 then what is the point of storing at 0.01 resolution? Just store how many 0.05s there are (divide by 0.05) then multiply it out again afterwards to get the original temperature. Most useful when coupled with a temperature difference to increase the storage range.</p> <p>There's many tricks, you see, and which work best depend exactly on what you want to do with the data.</p>
16807
|led|display|
4 Digit, 7 Segment Display Wiring (14 pin)
2015-10-13T16:02:19.257
<p>I purchased this 4 digit, 7 segment display from Adafruit:</p> <p>Product: <a href="http://www.adafruit.com/products/865" rel="nofollow">http://www.adafruit.com/products/865</a></p> <p>Data Sheet: <a href="http://www.adafruit.com/datasheets/865datasheet.pdf" rel="nofollow">http://www.adafruit.com/datasheets/865datasheet.pdf</a></p> <p>Everything I have searched for on the net either has 12 pins or 16 pins and most of those are only using 4 resistors. This one has 14 pins. I'm trying to wire it up to an Arduino but I'm not sure which pins should have resistors and which shouldn't. If I wire it up like in the product picture with 1k resistors, I get 8.8.:8.8. and as I remove resistors from 5V, I can see the different sections that are lit/not lit.</p> <p>Is that the correct way of doing it? Can I now just wire those to the Arduino?</p>
<p>It's just a 12 pin display, but with two extra pins for the colon.</p> <p>Removing connections can help you better understand what it going on. </p> <p>Resistor should be added to the anodes (pins 1,2,3,4,5,8,9,12,13) just like on the website. Pin 8 should be a different value, to match the brightness of the other (multiplexed) leds.</p> <p>The other end of the resistor can be put into the Arduino. Depending on the resistor value you may need to add some transistor to drive the other pins (cathodes) on the display. Lower value resistors means a brighter display, but too much current for the Arduino to drive all 8 leds of a digit at the same time. </p> <p>1k resistors, would mean about 3mA of current per segment. So if all segments are on in one digit, that would be 8*3, so 24mA. Which is approaching the maximum current an Arduino pin can source.</p>
16825
|arduino-mega|led|
LED matrix appears dead
2015-10-14T08:05:33.950
<p>I recently purchased a 1.2 8x8 yellow matrix from Adafruit, along with a HT16K33 backpack for it. I joined the matrix and the backpack, connected everything to the arduino, followed the instructions on the site and got it to work. During animation certain rows would not light up and upon later examination I realized that I had to solder up the pins to the backpack because some pins would not completely make contact with the backpack. After soldering the matrix to the backpack, I fired up arduino and uploaded the matrix8x8 sketch that comes with the library to test the matrix and nothing happens. </p> <p>I don't have a multimeter yet, but tried to check whether electricity is reaching the backpack which turns out to be true. (used a led and connected it to both + and -, and data and clock pins on the backpack.) in both cases the led lights up.</p> <p>How can I check the health of the backpack and/or matrix?</p>
<p>I hate to say it, but a multimeter would really come in handy for you. Harbor Freight has some for under $10.</p> <p>That said, without knowing anything specific about what you are using, you could try using the same LED you used to test power and put it in parallel with one of the LEDs on the matrix. I'm guessing you don't have power at the LEDs though because it seems unlikely that all the LEDs would fail. Check your solder work and make sure you have not shorted anything. Also, you could have overheated a component when soldering causing it to fail. Good luck.</p>
16831
|usb|
Detect USB activity from a host
2015-10-14T16:10:18.663
<p>I am testing a WinCE device that loses all USB communication infrequently. I need to detect when the USB fails on this device. When it fails, the power is intact at the port, just no data at all on D+ and D- (I verified this with an oscilloscope). This host device is basically a black box to me so I can't do anything to it but check it's state.</p> <p>My proposed solution: Use an arduino of some type (preferably an UNO since I have one already) programmed to detect USB activity to let me know when USB is failing on the host device I am testing.</p> <p>Is this possible? The arduino seems like a good solution for me because I assume it is a USB client, which I need in this scenario. Any example or pointing me in the right direction would be of great help. Thanks!</p>
<p>If all you are interested in is the voltages on the D+ and D- lines you could wire those direct into two ADC inputs on the Arduino and wire +5V and GND into the +5V and GND pin. The Arduino can then sample the voltages and compare them to valid or invalid ranges.</p>
16834
|digital|
Why cannot I input arrays as digitalWrite arguments?
2015-10-14T18:11:25.503
<p>I am making my own "7 segment LED driver". I know there is a lot of examples on the internet, I just want to try my own. But I have a piece of code that does not work and I don't know why. Can somebody explain to me why it is not working?</p> <p>When I put in this, it works:</p> <pre><code>digitalWrite(pins[0], one[0]); digitalWrite(pins[1], one[1]); digitalWrite(pins[2], one[2]); digitalWrite(pins[3], one[3]); digitalWrite(pins[4], one[4]); digitalWrite(pins[5], one[5]); digitalWrite(pins[6], one[6]); </code></pre> <p>So of course I tried using for():</p> <pre><code>for (byte i = 0; i &gt;= 6; i++) { digitalWrite(pins[i], one[i]); } </code></pre> <p>And this does not work. But why? I think it should. Btw. <em>pins</em> is const byte array and <em>one</em> is const bool array.</p> <p>Thanks in advance for any suggestions!</p>
<p>You've written the <code>for</code> loop incorrectly.</p> <pre><code>for (byte i = 0; i &gt;= 6; i++) &lt;-- ERROR HERE { digitalWrite(pins[i], one[i]); } </code></pre> <p>That first line should be <code>for (byte i = 0; i &lt;= 6; i++)</code>. <code>i</code> begins at zero, which is less than six, and the loop only runs while <code>i</code> is greater than 6.</p>
16837
|led|display|
Execute Code While Refreshing a 7 Segment LED Display
2015-10-14T19:01:03.433
<p>I'm using the following library to drive a 4 digit, 7 segment LED display:</p> <p><a href="http://playground.arduino.cc/Main/SevenSegmentLibrary" rel="nofollow">http://playground.arduino.cc/Main/SevenSegmentLibrary</a></p> <p>The display is showing the temperature which it gets from a DS18B20 temperature sensor. Since the LED display constantly needs to be refreshed, when the code runs to get the current temperature, the display temporarily turns off because the LEDs are not being refreshed. The code I am using is below. Is there anyway to prevent the LED display from turning off while the temperature request code runs?</p> <pre class="lang-c prettyprint-override"><code>#include &lt;SevSeg.h&gt; #include &lt;OneWire.h&gt; #include &lt;DallasTemperature.h&gt; SevSeg sevseg; unsigned long timer; // the timer unsigned long INTERVAL = 30000; // the repeat interval (30 seconds) #define ONE_WIRE_BUS 2 OneWire oneWire(ONE_WIRE_BUS); DallasTemperature sensors(&amp;oneWire); void setup() { byte numDigits = 4; byte digitPins[] = {A2, A3, A4, A5}; byte segmentPins[] = {8, 10, 6, 4, 3, 9, 7, 5}; sevseg.begin(COMMON_CATHODE, numDigits, digitPins, segmentPins); sevseg.setBrightness(90); // Get the initial temperature and show it on the LED display sensors.begin(); sensors.requestTemperatures(); sevseg.setNumber(sensors.getTempCByIndex(0), 1); timer = millis(); // start timer } void loop() { if ((millis()-timer) &gt; INTERVAL) { // Reset the timer and get/display the current temperature timer += INTERVAL; sensors.requestTemperatures(); sevseg.setNumber(sensors.getTempCByIndex(0), 1); } sevseg.refreshDisplay(); // Must run repeatedly to refresh the LED display } </code></pre>
<p>The problem here is that the display is driven using a timer interrupt. The temperature sensor, being a one-wire device, has to have very careful timing to communicate with it. As a result it disables interrupt so it has exclusive use of the CPU and can properly predict its timing while it's communicating. And so the display can't refresh at the same time.</p> <p>So what can you do? Well, nothing really. You can't have perfect timing for the temperature sensor while at the same time interrupting it for displaying the value.</p> <p>So there's really two main options:</p> <ol> <li><p>Change the temperature sensor. Use an SPI or I2C temperature sensor that has a real hardware interface to communicate with it so you don't have to use big-banging.</p></li> <li><p>Change the display. A non-multiplexed display or a display with its own built in driver (most often with some serial protocol like I2C or UART) would mean you don't have to use interrupts to update the display.</p></li> </ol> <p>Basically you have two technologies that won't sit together well on the same chip.</p> <hr> <p>Update:</p> <p>I missed the <code>sevseg.refreshDisplay()</code> function call since the website had scrolled it off the bottom of the code block. Bah!</p> <p>Ok, so it's not using an interrupt. That could be a good thing, or it may be meaningless. It takes time to do the temperature reading, and it's that getting in the way of the refreshing.</p> <p>There's a chance you may be able to push the update "into the background" by attaching it to a timer interrupt, but if the OneWire communication does disable interrupts then the problem will still persist (I don't have OneWire to hand to look at the code right now).</p>
16850
|arduino-mega|bootloader|
Arduino Mega 2560 bootloader delay
2015-10-15T11:16:31.913
<p>I need to make my program run immediately on a reset or power up. However, the bootloader delays program startup by around 2.5 seconds. How can I get over this? Is there a way to turn off the bootloader wait period?</p>
<p>Yes. You remove the bootloader completely and program the Arduino using a hardware programmer.</p> <p>If you could "turn off" the wait period you would never be able to get into the bootloader to program the board, so the bootloader would be completely useless. So either way you would then need a hardware programmer to do anything constructive with the board.</p> <p>A hardware programmer could be another Arduino, or a real hardware programming adapter.</p>
16855
|arduino-uno|esp8266|
Where can I storage a local database?
2015-10-15T16:31:52.857
<p>I want to create a website where the users can have their own database. An example: - An user will receive some data from HTTP POST and I want to storage all the information into a local database to access to it. For example, the URL that the user has visited in the last month.</p> <p>I know that the best option will be to create a database in my server and put each user in it, but it will be very long database and the information between users is not shared, therefore it will be more secure using a local database, but I don´t know if that can be done.</p> <p>My project is about ESP8266 and uploading data to a server, so this can be done using a microcontroller instead the computer. I have seen the raspberry to use it as a server and storage there the database, but it is so expensive. Can be done using another board as Arduino, Texas Instruments, etc...</p> <p>The main aim is to create a main hub to storage all the values received from the ESP8266 and then share over internet, but I don´t know how to build a hub where I can store a database inside and a HTML website to show the values. Any ideas? I would like to avoid a computer to do it.</p> <p>I think in something for less than 10 GBP, because I bought and Arduino and Ethernet shield for 5 GBP both, fake version, but useful for my project</p>
<p>As I understand the question, you want a 'mini' database for your ESP8266, without the need to connect to the internet.</p> <p>One way I can think of is that you could use your ESP8266 flash memory to store the database. Use SPIFFS with, say, 1 MBytes flash size, leaving 3 MBytes for your actual program (assuming the ESP8266 has 4 MB flash memory). More than 20 thousand record files for 50 bytes each.</p> <p>But you'll need to write your own create, read, update, delete (CRUD) function to handle the files.</p> <p>If someone has already written such functions, that would be useful to share here.</p>
16860
|arduino-uno|sensors|
Ping sensor with three or four pins?
2015-10-15T18:28:40.027
<p>I bought a <a href="https://www.arduino.cc/en/Tutorial/Ping" rel="nofollow">Ping Ultrasonic Range Finder</a>. It has four pins that you connect to the Arduino. I see in Internet that they have three pins. What does represent each pin and where to connect it to? I have an Arduino Uno Starter Kit.</p>
<p>You have 4 <em>pins</em>.</p> <ul> <li>Vcc: +5V supply voltage (it stands for Collector Voltage)</li> <li>GND: Ground.</li> <li>Trig: Causes an ultrasound pulse to be generated (it stands for <em>Trigger</em>)</li> <li>Echo: Tells you when an echo has been received.</li> </ul> <p>You can see how to wire and use it here: <a href="http://www.instructables.com/id/Easy-ultrasonic-4-pin-sensor-monitoring-hc-sr04/" rel="nofollow">http://www.instructables.com/id/Easy-ultrasonic-4-pin-sensor-monitoring-hc-sr04/</a></p>
16862
|gsm|gps|adafruit|components|
What components I need for a small GPS tracker
2015-10-15T18:42:42.000
<p>I am new to Arduino and want to create a graduation project for my university. I am thinking to create a GPS tracker that can be attached to a cloth to track kids, for example. So the requirements for this project is as follows: - The device should be small - It should upload its location to a web server constantly. - the device should work with battery for at least 8 hours</p> <p>Now what components are needed for this project? What concern me a lot is that how can I find battery last this much time, if I need bigger battery, it may hinder the device from being attached easily.</p>
<p>You have two options. Option 1. Buy a ready made pet tracking device from online market e.g (<a href="https://www.aliexpress.com/item/Pets-Smart-Mini-GPS-Tracker-Anti-Lost-Waterproof-Bluetooth-Tracer-For-Pet-Dog-Cat-Keys-Wallet/32887784462.html?spm=2114.search0104.3.1.26793604pFMLma&amp;ws_ab_test=searchweb0_0,searchweb201602_3_10065_10068_319_10059_10884_317_10887_10696_321_322_10084_453_10083_454_10103_10618_10307_537_536,searchweb201603_52,ppcSwitch_0&amp;algo_expid=09c58262-a0e7-4205-8fba-cd8265c15b3e-0&amp;algo_pvid=09c58262-a0e7-4205-8fba-cd8265c15b3e" rel="nofollow noreferrer">https://www.aliexpress.com/item/Pets-Smart-Mini-GPS-Tracker-Anti-Lost-Waterproof-Bluetooth-Tracer-For-Pet-Dog-Cat-Keys-Wallet/32887784462.html?spm=2114.search0104.3.1.26793604pFMLma&amp;ws_ab_test=searchweb0_0,searchweb201602_3_10065_10068_319_10059_10884_317_10887_10696_321_322_10084_453_10083_454_10103_10618_10307_537_536,searchweb201603_52,ppcSwitch_0&amp;algo_expid=09c58262-a0e7-4205-8fba-cd8265c15b3e-0&amp;algo_pvid=09c58262-a0e7-4205-8fba-cd8265c15b3e</a>). Then you can download the app and start tracking movement.</p> <p>Option 2: The other alternative is to build one from scratch by purchasing all the necessary components. This is option is most appropriate for students. You can check this page for more <a href="https://electronicsforu.com/electronics-projects/hardware-diy/gsm-gps-based-vehicle-tracking-system" rel="nofollow noreferrer">https://electronicsforu.com/electronics-projects/hardware-diy/gsm-gps-based-vehicle-tracking-system</a>. However, you may not be able to achieve the small size as you wanted but you should have something close to it if you carefully select your components.</p>
16865
|spi|
Send numbers bigger than 256 by SPI
2015-10-15T19:35:12.733
<p>How can i send numbers like 300 or 1024 ?</p> <p>I'm using the recommendation of the atmel's manual.</p> <pre><code>void SpiTransmitir(unsigned char data) { SPDR = data; while(!(SPSR &amp; (1&lt;&lt;SPIF)));//{Serial.println("While");} } </code></pre> <p>I imagined that one bit shift could be the solution, but it still fails.</p>
<p>Try to join the numbers as follows: </p> <pre><code>#define NUMERO 342 void setup() { Serial.begin(9600); Serial.println(NUMERO, BIN); // Mostra valor do número em binário uint8_t MSB = 0, LSB = 0; // Dois números de 8 bits uint16_t junta = 0; // Valor junto em 16 bits MSB = NUMERO &gt;&gt; 4; LSB = NUMERO &lt;&lt; 4; junta = (MSB &lt;&lt; 4) | (LSB &gt;&gt; 4) ; Serial.println(junta, BIN); } void loop() {} </code></pre>
16870
|c++|button|debounce|
Help with button library, hold>2s doA else doB
2015-10-15T21:38:02.447
<p>I'm using <a href="https://github.com/JChristensen/Button" rel="nofollow" title="JChristensen&#39;s Button Library">JChristensen's Button Library</a> to debounce my buttons and provide extra functionality. I'm trying to use his press &amp; hold function to do something if the button is pressed and held for greater than 2 seconds. If it is just pressed momentarily it should do something else. His example use switch cases, and I couldn't get it to work. Here is my example that currently doesn't work. </p> <pre><code> #include &lt;Button.h&gt; #include &lt;SPI.h&gt; #include &lt;printf.h&gt; // Keypress state setup byte clearPin = 16; // Clear pin #define PULLUP true #define INVERT true // Since the pullup resistor will keep the pin high unless the #define DEBOUNCE_MS 20 // A debounce time of 20 milliseconds usually works well for tactile button switches. #define LONG_PRESS 2000 // We define a "long press" to be 2000 milliseconds. unsigned long ms; // The current time from millis() Button clearBtn(clearPin, PULLUP, INVERT, DEBOUNCE_MS); // Declare the button int score=1; void setup () { pinMode(16, INPUT_PULLUP); // Pin for clear button Serial.begin(9600); // Radio Setup } void loop() { clearScore(); // sets both home and away scores to 0 or enters settings menu } void clearScore() { ms = millis(); //record the current time clearBtn.read(); // Read the button if (clearBtn.pressedFor(2000)) { // Enter settings menu Serial.println("Settings Menu"); while (clearBtn.read()!=1) { } // End While return; // Hopefully not proceed down to the next if } if (clearBtn.wasReleased() &amp;&amp; !clearBtn.pressedFor(2000)) { score=0; Serial.println("Clearing Scores"); delay(50); } } </code></pre> <p>Can anyone help please? My serial output repeats "Settings Menu" over and over. Once I let go of the button <s>variable1</s> always gets set to 0.</p>
<p>The <code>loop()</code> and <code>clearScore()</code> code that you have is like the following.</p> <pre><code>void loop() { clearScore(); // sets both home and away scores to 0 or enters settings menu } void clearScore() { ms = millis(); //record the current time clearBtn.read(); // Read the button if (clearBtn.pressedFor(2000)) { // Enter settings menu Serial.println("Settings Menu"); while (clearBtn.read()!=1) { // do stuff } // End While return; // Don't proceed to next if } if (clearBtn.wasReleased() &amp;&amp; !clearBtn.pressedFor(2000)) { score=0; Serial.println("Clearing Scores"); delay(50); } } </code></pre> <p>When you reset the Arduino and then hold down the clearBtn, <code>clearScore()</code> will be called repeatedly. <code>clearBtn.pressedFor(2000)</code> will not be satisfied during the first two seconds of holding the button down, and <code>clearBtn.wasReleased()</code> will not be satisfied either, so <code>clearScore()</code> will do nothing during the first two seconds. </p> <p>After the first two seconds, "Settings Menu" will be sent repeatedly: <code>clearBtn.pressedFor(2000)</code> is true, so the first <code>if</code> succeeds each time <code>clearScore()</code> runs, and it will run repeatedly because it is called from <code>loop()</code>. The <code>while</code> test, <code>clearBtn.read()!=1</code> [which in more-idiomatic C would be written as <code>!clearBtn.read()</code>] fails until the clearBtn is released, so the <code>while</code> loop does nothing. Also, <code>clearBtn.wasReleased()</code> will be false, so the other <code>if</code> does nothing.</p> <p>When the button finally is released, <code>clearBtn.pressedFor(2000)</code> goes false, so the first <code>if</code> fails and the second executes one time.</p> <p>Here is some code that should act more like what you want, as expressed in your comment, </p> <blockquote> <p>It's supposed to work like this: 1) hold button down for 2 seconds to enter settings menu. While in settings menu I'll code other stuff. Stay in settings menu until the clear button is pressed momentarily again. Once you press clear button again from being in the settings menu, the score should NOT be reset, and it should just return to the main loop. 2) if the clear button was not pressed for more than 2 seconds, just clear the score.</p> </blockquote> <pre><code>void clearScore() { ms = millis(); //record the current time while (clearBtn.read()) { if (clearBtn.pressedFor(2000)) { Serial.println("Settings Menu"); // Announce Settings menu while (clearBtn.read()) {} // Await button release while (!clearBtn.read()) { // Await button press // do Settings menu stuff here // (possibly wait for clearBtn release, to // avoid immediately clearing score again) } } return; } if (clearBtn.wasReleased()) { // See if released, after short press score=0; Serial.println("Clearing Scores"); delay(50); } } </code></pre> <p><em>Edit edit:</em> To avoid resetting the score at every settings exit, in the above code replace</p> <pre><code> // (possibly wait for clearBtn release, to // avoid immediately clearing score again) } } </code></pre> <p>with</p> <pre><code> } } while (clearBtn.read()) {} // wait for the settings-exit clearBtn release clearBtn.read(); // Do another read to avoid clearing score on next clearScore() </code></pre> <p>That is, right before the <code>return</code>, wait for clearBtn release, and read it again to be sure later reads won't register a release. The latter <code>read</code> might not be needed, because <code>clearScore()</code> does a <code>read</code> when it tests the first <code>while</code> condition; you could experiment.</p>
16878
|arduino-uno|esp8266|relay|
ESP8266 stops responding when isolated relay is connected to AC tubelight
2015-10-16T03:56:33.127
<p>I'm completely new to Arduino and do not have an electronics background. I'm really keen to do a POC on home automation. As a start, I decided to switch on a tube light using ESP8266, Arduino Uno R3 and isolated relay. I have read that this can be done without arduino also.</p> <p>I'm able to switch on and switch off the relay without any problem. But when the relay is connected to the tube light, the ESP8266 stops responding. I couldn't find what was causing the issue.</p> <p>I also read that the ESP2866 should be powered properly to function correctly. I'm following the wiring schema 5 mentioned in the link <a href="http://yaab-arduino.blogspot.in/2015/03/esp8266-wiring-schemas.html" rel="nofollow noreferrer">http://yaab-arduino.blogspot.in/2015/03/esp8266-wiring-schemas.html</a>.</p> <p><a href="https://i.stack.imgur.com/2ic8q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2ic8q.png" alt="enter image description here" /></a></p> <p>This is my code.</p> <pre class="lang-c prettyprint-override"><code>#include &lt;SoftwareSerial.h&gt; #define DEBUG true int relay = 8; SoftwareSerial esp8266(2, 3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3. // This means that you need to connect the TX line from the esp to the Arduino's pin 2 // and the RX line from the esp to the Arduino's pin 3 void setup() { Serial.begin(9600); esp8266.begin(115200); // your esp's baud rate might be different pinMode(relay, OUTPUT); digitalWrite(relay, LOW); sendData(&quot;AT+RST\r\n&quot;, 2000, DEBUG); // reset module sendData(&quot;AT+CWMODE=3\r\n&quot;, 1000, DEBUG); // configure as access point sendData(&quot;AT+CWJAP=\&quot;xxxx\&quot;,\&quot;xxx\&quot;\r\n&quot;, 5000, DEBUG); // configure as access point sendData(&quot;AT+CIPMUX=1\r\n&quot;, 1000, DEBUG); // configure for multiple connections sendData(&quot;AT+CIPSERVER=1,80\r\n&quot;, 1000, DEBUG); // turn on server on port 80 sendData(&quot;AT+CIFSR\r\n&quot;, 5000, DEBUG); // get ip address sendData(&quot;AT+CIFSR\r\n&quot;, 5000, DEBUG); // get ip address } void loop() { if (esp8266.available()) // check if the esp is sending a message { if (esp8266.find(&quot;+IPD,&quot;)) { delay(1000); int connectionId = esp8266.read() - 48; // subtract 48 because the read() function returns // the ASCII decimal value and 0 (the first decimal number) starts at 48 if (esp8266.find(&quot;==&quot;)) { Serial.print(&quot;State : &quot;); char c = esp8266.read(); Serial.print(c); if (c == '1') { digitalWrite(relay, HIGH); } else { digitalWrite(relay, LOW); } } String webpage = &quot;A&quot;; String cipSend = &quot;AT+CIPSEND=&quot;; cipSend += connectionId; cipSend += &quot;,&quot;; cipSend += webpage.length(); cipSend += &quot;\r\n&quot;; sendData(cipSend, 1000, DEBUG); sendData(webpage, 1000, DEBUG); String closeCommand = &quot;AT+CIPCLOSE=&quot;; closeCommand += connectionId; // append connection id closeCommand += &quot;\r\n&quot;; sendData(closeCommand, 3000, DEBUG); } } } String sendData(String command, const int timeout, boolean debug) { String response = &quot;&quot;; esp8266.print(command); // send the read character to the esp8266 long int time = millis(); while ( (time + timeout) &gt; millis()) { while (esp8266.available()) { // The esp has data so display its output to the serial window char c = esp8266.read(); // read the next character. response += c; } } if (debug) { Serial.print(response); } return response; } </code></pre> <p>The above code works perfectly until I connect the tube light to the relay. The power supply used in 9v 1A wall adapter.</p> <p>The relay used is <a href="http://www.amazon.in/gp/product/B00LL0M6RS?psc=1&amp;redirect=true&amp;ref_=oh_aui_detailpage_o03_s00" rel="nofollow noreferrer">http://www.amazon.in/gp/product/B00LL0M6RS?psc=1&amp;redirect=true&amp;ref_=oh_aui_detailpage_o03_s00</a>.</p> <p>The v+ of the relay is connected directly to the wall adapters voltage and ground to ground of wall adapter. The input of the relay is connected to Arduino digital pin 8.</p> <p>I'm really struggling hard to proceed here. Any help or hint would be much appreciated.</p> <p>Thanks in advance.</p>
<p>Finally I got this working using only ESP8266 and minor tweaks. I'll post the circuit here just in case if somebody is trying to do the same thing.</p> <p>Please note that this was done as a POC and I'm not from an electronics background.</p> <p><a href="https://i.stack.imgur.com/u316J.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u316J.png" alt="enter image description here"></a> </p> <p>Kindly note the blue wire from the GPIO 01 to resistor and an LED. I had to do this because when the circuit is powered on a HIGH signal is sent from the GPIO and the relay is turned on. I think it is the default behaviour of ESP8266. To suppress this initial flow, I did this (There may be a better way to do this according to electronics experts).</p> <p>Diode used is 1N4001 Diode</p> <p>Decoupling capacitor is - 10nf/100V (0.01uf/100V) Box Capacitor - Polyester</p> <p>Relay used is <a href="http://www.amazon.in/gp/product/B00LL0M6RS?psc=1&amp;redirect=true&amp;ref_=oh_aui_detailpage_o05_s00" rel="nofollow noreferrer">http://www.amazon.in/gp/product/B00LL0M6RS?psc=1&amp;redirect=true&amp;ref_=oh_aui_detailpage_o05_s00</a></p> <p>Transistor is bc547.</p> <p>Before connecting the devices, I flashed nodemcu firmware to ESP8266 so that I can write code in Lua script. Refer any of these to flash the firmware - <a href="https://www.youtube.com/watch?v=Gh_pgqjfeQc" rel="nofollow noreferrer">https://www.youtube.com/watch?v=Gh_pgqjfeQc</a> <a href="https://www.youtube.com/watch?v=pp6O96B1-Jk" rel="nofollow noreferrer">https://www.youtube.com/watch?v=pp6O96B1-Jk</a></p> <p>I used LuaLoader to transfer the following code to the ESP8266. <a href="http://randomnerdtutorials.com/esp8266-web-server/" rel="nofollow noreferrer">http://randomnerdtutorials.com/esp8266-web-server/</a></p> <p>I'm posting my init.lua below.</p> <p><strong>init.lua</strong></p> <pre><code>wifi.setmode(wifi.STATION) wifi.sta.config("&lt;ssid&gt;","&lt;password&gt;") cfg = { ip="192.168.1.101", netmask="255.255.255.0", gateway="192.1681.1" } wifi.sta.setip(cfg) print(wifi.sta.getip()) led1 = 3 led2 = 4 gpio.mode(led1, gpio.OUTPUT) gpio.mode(led2, gpio.OUTPUT) gpio.write(led1, gpio.LOW) gpio.write(led1, gpio.LOW) srv=net.createServer(net.TCP) srv:listen(80,function(conn) conn:on("receive", function(client,request) print("receive") local buf = ""; local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP"); if(method == nil)then _, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP"); end local _GET = {} if (vars ~= nil)then for k, v in string.gmatch(vars, "(%w+)=(%w+)&amp;*") do _GET[k] = v end end buf = buf.."&lt;html&gt;&lt;head&gt;&lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt; Control Panel&lt;/h1&gt;"; buf = buf.."&lt;p&gt;Tubelight &lt;a href=\"?pin=ON1\"&gt;&lt;button&gt;ON&lt;/button&gt;&lt;/a&gt;&amp;nbsp;&lt;a href=\"?pin=OFF1\"&gt;&lt;button&gt;OFF&lt;/button&gt;&lt;/a&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;"; local _on,_off = "","" print(wifi.sta.getip()) if(_GET.pin == "ON1")then gpio.write(led1, gpio.HIGH); elseif(_GET.pin == "OFF1")then gpio.write(led1, gpio.LOW); elseif(_GET.pin == "ON2")then gpio.write(led2, gpio.HIGH); elseif(_GET.pin == "OFF2")then gpio.write(led2, gpio.LOW); end client:send("HTTP/1.1 200 OK\r\n"); client:send("Content-type: text/html\r\n"); client:send("Connection: close\r\n\r\n"); client:send(buf); client:close(); collectgarbage(); end) end) </code></pre> <p>If everything is running, connect your phone or computer to the same wifi using "<code>&lt;ssid&gt;</code>","<code>&lt;password&gt;</code>" and access the IP 192.168.1.101 to see a webpage with one buttons "ON" and "OFF". Click on it an check whether it is working.</p>
16880
|usb|linux|
How to wait Arduino ready with ANY method?
2015-10-16T05:51:54.917
<p>Recently I knew, that Arduino restarts any time somebody accesses it's serial port. I was trying to use this feature so that for each request Arduino restarts and give answer on request. Unfortunately, I found this is impossible with shell script, because shell script can't keep port open all time I send requests and wait responses: Arduino restarts on each port touch.</p> <p>So, I wrote simple C++ program:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;fstream&gt; using namespace std; void help() { cout &lt;&lt; "bmp180dims usage:" &lt;&lt; endl &lt;&lt; "bmp180dims port command" &lt;&lt; endl; } int main(int argc, char* argv[]) { if( argc != 3 ) { help(); return 0; } fstream port; string answer; port.open(argv[1], std::fstream::in | std::fstream::out); port &lt;&lt; argv[2] &lt;&lt; endl; port &gt;&gt; answer; cout &lt;&lt; answer &lt;&lt; endl; port.close(); return 0; } </code></pre> <p>Since this program has explicit <code>open</code> and <code>close</code> statements, I was thinking, this program will wait for Arduino answer, because of stream reading functions. But I failed again: this program returns nothing as if it is not waiting.</p> <p>Why? </p> <p>Apparently, the only way to communicate with Arduino, is to have daemon program, which always listen it's port. Is this really so?</p> <p>Arduino-side code is here: <a href="https://arduino.stackexchange.com/questions/16769/how-can-program-arduino-restarted-by-ide">How can program/arduino restarted by IDE?</a></p>
<p>Again, you're <em>not waiting for the bootloader to complete</em> before sending your text:</p> <pre><code>port.open(argv[1], std::fstream::in | std::fstream::out); // Board resets and enters bootloader port &lt;&lt; argv[2] &lt;&lt; endl; // You send argv[2] to the bootloader port &gt;&gt; answer; // The bootloader doesn't understand what you sent so doesn't reply with anything </code></pre> <p>You <em>must</em> wait for the bootloader to complete <em>before</em> sending ANYTHING to the Arduino.</p> <p>The two ways you can do that are:</p> <ol> <li>Insert a <code>sleep(3);</code> immediately after opening the port to give the bootloader a chance to time out and start running your sketch, or</li> <li>Provide an initial "I Am Ready" message from your sketch that your C++ program waits for <em>before</em> sending the text you want to send to elicit an answer.</li> </ol>
16910
|arduino-uno|gsm|gps|
Problem in receieving message
2015-10-17T14:05:28.680
<p>I'm working on a project in which when I press reset button the arduino should send longitudes and latitudes to my phone. I'm a beginner and tried to join two codes, first code can send the message and the second code can get the lon and lat printed on the serial monitor.</p> <p>First code--</p> <pre><code>int timesTosend=1; int count=0; char phone_no[]="+917771914436"; void setup() { Serial.begin(9600); delay(2000); Serial.println("AT+CMGF=1"); delay(200); } void loop() { while (count&lt;timesTosend) { delay(1500); Serial.print("AT+CMGS=\""); Serial.print(phone_no); Serial.println("\""); while(Serial.read()!='&gt;'); { Serial.print("Hii If this message is sent then its a huge sucess for me"); delay(500); Serial.write(0x1A); Serial.write(0x0D); Serial.write(0x0A); delay(5000); } count++; } } </code></pre> <p>Second code--</p> <pre><code>#include &lt;SoftwareSerial.h&gt; #include &lt;TinyGPS.h&gt; long lat,lon; // create variable for latitude and longitude object SoftwareSerial gpsSerial(4, 3); // create gps sensor connection TinyGPS gps; // create gps object void setup(){ Serial.begin(9600); // connect serial gpsSerial.begin(9600); // connect gps sensor } void loop(){ while(gpsSerial.available()){ // check for gps data if(gps.encode(gpsSerial.read())){ // encode gps data gps.get_position(&amp;lat,&amp;lon); // get latitude and longitude // display position Serial.print("Position: "); Serial.print("lat: ");Serial.print(lat);Serial.print(" ");// print latitude Serial.print("lon: ");Serial.println(lon); // print longitude } } } </code></pre> <p>My code which is not working--</p> <pre><code>#include &lt;SoftwareSerial.h&gt; #include &lt;TinyGPS.h&gt; long lat,lon; // create variable for latitude and longitude object SoftwareSerial gpsSerial(4, 3); // create gps sensor connection TinyGPS gps; // create gps object void setup() { Serial.begin(9600); // connect serial gpsSerial.begin(9600); // connect gps sensor Serial.begin(9600); delay(2000); Serial.println("AT+CMGF=1"); delay(200); } int timesTosend=1; int count=0; char phone_no[]="+917771914436"; void loop() { while (count&lt;timesTosend) { delay(1500); Serial.print("AT+CMGS=\""); Serial.print(phone_no); Serial.println("\""); while(Serial.read()!='&gt;'); { while(gpsSerial.available()) { if(gps.encode(gpsSerial.read())) { // encode gps data gps.get_position(&amp;lat,&amp;lon); // get latitude and longitude Serial.print(lat,lon); delay(500); Serial.write(0x1A); Serial.write(0x0D); Serial.write(0x0A); delay(5000); } } } count++; } } </code></pre> <p>Please help me out by correcting my mistake in the code.</p>
<pre><code>Serial.print(lat,lon); </code></pre> <p>That doesn't do what you think it does. That is trying to print the latitude encoded in base "lon", which just isn't going to work.</p> <p>Instead you need to send it as separate operations:</p> <pre><code>Serial.print(lat); Serial.print(","); Serial.print(lon); </code></pre> <p>Also you should separate out the GPS and GSM routines. Create a function that gets the latitude and longitude, and another function that sends the two values as a text message. Then you can keep things as discrete obvious steps and not get confused with what is happening when.</p>
16917
|arduino-ide|pins|hardware|esp8266|
Esp8266 V12 Wiring
2015-10-17T15:53:42.390
<p>I have tried a Google search and cannot find any place that tells me exactly how to wire the version 12 esp8266 ,</p> <p>How should it be wired for normal operation and for flashing ?</p> <p>I am designing a diy pcb and need to know the specifics,to wire a switch for flashing purposes etc.I am using just a esp8266 version 12 standalone without a typical arduino micro-controller attached and will be flashing it to take the arduino ide ,any help with this would be great as I'm sure someone has already come across this problem.</p>
<p>You could find the <a href="http://www.instructables.com/id/Getting-Started-with-the-ESP8266-ESP-12/?ALLSTEPS#step3" rel="nofollow noreferrer">solution</a>, on the first hit for googling "ESP8266 ESP-12".</p> <blockquote> <p><a href="https://i.stack.imgur.com/r9Zj3.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r9Zj3.jpg" alt="wiring"></a></p> <p>You need to connect a few GPIO pins on the ESP-12 to 3.3V or Ground, to set it in the right mode for communicating with it. Here are the connections you need to make :</p> <p>VCC ----> 3.3V Power supply (Vout of LM1117)</p> <p>GND ----> Ground of power supply</p> <p>CH_PD ----> HIGH (3.3V)</p> <p>GPIO2 ----> HIGH (3.3V)</p> <p>GPIO15 ----> LOW (GND)</p> <p>GPIO0 ----> HIGH or Floating for AT Mode (3.3V) [ * if you want to flash completely different firmware then you must connect it to ground ]</p> </blockquote> <p>You need to connect <code>GPIO0</code> to <code>GND</code> for flashing and to <code>VCC</code> for normal operation.</p>
16928
|power|
Can one supply an Arduino Zero's VIN pin with 5v?
2015-10-17T22:48:12.367
<p>The title pretty much says it all. I know that most Arduinos can do this, but I couldn't find very much information for the Zero. Any help would be very much appreciated.</p>
<p>Yes you can. If you look at the schematics on the Arduino website you can see that the 3.3 volt regulator is connected to the 5 volt regulator. That means that if you feed 5 volts straight into the 5 volt pin it will go through the 3.3 volt regulator to supply the main chip. Note that this is going into the 5 volt pin not the VIN pin which goes into the 5 volt regulator and would thus require a higher voltage than 5 volts.</p>
16933
|arduino-uno|string|
Read sensor and convert reading to const char*
2015-10-17T23:59:17.293
<p>I'm working on a home automation project using Arduino and MQTT.</p> <p>I've found a problem and my limited programming knowledge find a way to solve it.</p> <p>I can send text trough MQTT normally, using</p> <pre><code>client.Publish("some/topic","Some text here"); </code></pre> <p>But when I try to send a variable (int, char, etc), the compiler says "invalid conversion from 'char' to 'const char*' [-fpermissive]"</p> <p>How can I store DHT11 sensor reading in const char* to send it?</p> <p>BTW, I've found <a href="http://e.verything.co/post/61576413925/publishing-arduino-sensor-data-through-mqtt-over" rel="nofollow">this</a> code where </p> <pre><code>char *tempC; tempC = dtostrf(((((analogRead(tempPinIn) * 5.0) / 1024) - 0.5) * 100), 5, 2, message_buffer); client.publish("arduino/temperature",tempC); </code></pre> <p>is used. But the extra sensor calibration makes it even harder for me to understand whats going on. </p>
<p>The function <code>dtostrf()</code> is prototyped as:</p> <pre><code>char *dtostrf (double val, signed char width, unsigned char prec, char *sout); Where: val Your float variable; width Length of the string that will be created INCLUDING decimal point; prec Number of digits after the deimal point to print; sout Destination of output buffer; </code></pre> <p>An example of usage is as follows:</p> <pre><code>/* OPTION ONE */ char msgBuffer[20]; // make sure this is big enough to hold your string char *pointer_to_created_string; float testFloat = 123.45; pointer_to_created_string = dtostrf(testFloat, 6, 2, msgBuffer); client.Publish("...topic...", pointer_to_created_string); /* OPTION TWO */ char msgBuffer[20]; // make sure this is big enough to hold your string float testFloat = 123.45; client.Publish("...topic...", dtostrf(testFloat, 6, 2, msgBuffer)); </code></pre> <p>Don't be put off by the code in the link you included in your question. The first argument sent to <code>dtostrf</code> (everything before the first comma) is nothing more than a some calculations bundled into one single line.</p>
16940
|arduino-uno|arduino-ide|robotics|python|
Advanced Line Follower robot
2015-10-18T06:02:32.407
<p>I know about line follower mainly the grid solving robots i know the basics actually. Actually they have to trace the path of the grid in an arena and then reach back to starting point in a shortest distance. Here my doubt is regarding the line follower in this link I have attached.<a href="https://www.youtube.com/watch?v=5At_u5rnh2U" rel="nofollow">Advanced Line Follower Robot for maze solving</a></p> <p>My doubt is what are the procedures to do it? They have mapped the path and used Dijkstra algorithm to solve the path. But how do they transfer the code(i.e) where it has to turn which direction it has to turn. how are they generating the what function should be passed? Please explain i need the procedure alone. am going to try it with python.</p>
<p>Any language will do, as long as it is supported by your HW platform. If you want to use python, you need a board that can run python. That could be an Arduino Yun, for example. Or an Intel Quark. Or an Intel Edison with an Arduino shield. But these will be expensive.</p> <p>You could, alternatively, use C/C++ and an Ardino UNO (or micro, nano, mini pro), which is far cheaper.</p> <p>Googling for something as simple as "Arduino line following kit" gives as first answer <a href="http://www.instructables.com/id/Line-following-Robot-with-Arduino/?ALLSTEPS" rel="nofollow">this</a>, which seems to be exactly what you are looking for.</p>
16953
|bluetooth|hc-05|
Problem activating HC-05 AT command mode with Arduino Uno Bluetooth shield
2015-10-18T12:09:59.103
<p>Please be gentle with me. I am attempting to modify the configurations of my HC-05 bluetooth module by using the AT command set. The method by which I'm trying to do this is by implementing the following connection:</p> <p>HC-05 GND --> Arduino GND; HC-05 3.3v --> Arduino 3.3V; HC-05 TX --> Arduino Pin 10; HC-05 RX --> Arduino Pin 11; HC-05 KEY --> Arduino Pin 9</p> <p><a href="https://i.stack.imgur.com/0ddBN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0ddBN.png" alt="enter image description here"></a></p> <p>This is the code which I uploaded to my Arduino (btw my arduino uno is an SMD clone): (code's from <a href="http://www.instructables.com/id/Modify-The-HC-05-Bluetooth-Module-Defaults-Using-A/step2/The-Arduino-Code-for-HC-05-Command-Mode/" rel="nofollow noreferrer">http://www.instructables.com/id/Modify-The-HC-05-Bluetooth-Module-Defaults-Using-A/step2/The-Arduino-Code-for-HC-05-Command-Mode/</a>)</p> <pre><code>#include &lt;SoftwareSerial.h&gt; SoftwareSerial BTSerial(10, 11); // RX | TX void setup() { pinMode(9, OUTPUT); // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode digitalWrite(9, HIGH); Serial.begin(9600); Serial.println("Enter AT commands:"); BTSerial.begin(38400); // HC-05 default speed in AT command more } void loop() { // Keep reading from HC-05 and send to Arduino Serial Monitor if (BTSerial.available()) Serial.write(BTSerial.read()); // Keep reading from Arduino Serial Monitor and send to HC-05 if (Serial.available()) BTSerial.write(Serial.read()); } </code></pre> <p>The problem is I can't seem to activate the AT mode. I don't get any response from the Serial Monitor whatever AT command I try. I double-checked the wiring and it's all good. I can't figure out what the problem is.</p>
<p>In <code>setup()</code> put pin 9 to low, and delay it for about 1 second and then put it to high.</p>
16954
|bluetooth|hc-05|
Problems connecting reliably using HC-05 (as bluetooth master)
2015-10-18T13:52:37.693
<p>I currently try to connect an Arduino Micro/Leonardo/32u4 to an ELM327 Bluetooth dongle using a HC-05 Bluetooth shield from iTeadStudio. I also have similar problems trying to connect to a bluetooth dongle (with added serial connection) on my PC.</p> <p>The basic AT-command communication works, but I haven't found out yet why AT+PAIR or AT+LINK are failing and what should be done to avoid this (I've done dozens of Serial Monitor command iterations). Until now I haven't found a command sequence that reliably connects. What I've tried so far (from different documentation and example codes):</p> <p>Check general AT command set:</p> <pre><code>AT &gt; OK </code></pre> <p>Reset to default values:</p> <pre><code>AT+ORGL &gt; OK </code></pre> <p>Set master mode and check it:</p> <pre><code>AT+ROLE=1 &gt; OK AT+ROLE? &gt; +ROLE:1 &gt; OK </code></pre> <p>Connect only to the specified bluetooth address:</p> <pre><code>AT+CMODE=0 &gt; OK </code></pre> <p>Reset and initialize:</p> <pre><code>AT+RESET &gt; OK AT+INIT &gt; OK </code></pre> <p>Configure inquiring mode:</p> <pre><code>AT+INQM=1,9,48 &gt; OK </code></pre> <p>Inquire:</p> <pre><code>AT+INQ &gt; +INQ:12:34:567890:1F1F,7FFF &gt; OK AT+STATE? &gt; +STATE:INQUIRING </code></pre> <p>Try to stop inquiring:</p> <pre><code>AT+INQC &gt; OK AT+STATE? &gt; +STATE:INQUIRING &gt; OK </code></pre> <p>Reset and initialize again (otherwise we can't leave the inquiring state):</p> <pre><code>AT+RESET &gt; OK AT+INIT &gt; OK AT+STATE? &gt; +STATE:INITIALIZED &gt; OK </code></pre> <p>Try to pair with the found device (my PC asks for the 1234-password and creates a serial port):</p> <pre><code>AT+PAIR=12,34,567890,20 &gt; OK AT+STATE? &gt; +STATE:PAIRED </code></pre> <p>Try to connect</p> <pre><code>AT+BIND=12,34,567890 &gt; OK AT+LINK=12,34,567890 &gt; FAIL ... </code></pre> <p>Does someone have some hints for finding the right sequence?</p>
<p>It looks like I now have a slight understanding of what happens and how to get the HC-05 working.</p> <p>Be sure to have the CMD-DAT-switch set to CMD before turning on the HC-05.</p> <p><strong>Command mode (configuration)</strong></p> <p>Check general AT command set:</p> <pre><code>AT &gt; OK </code></pre> <p>Reset to default values (sets, among others, ROLE=0 and CMODE=1):</p> <pre><code>AT+ORGL &gt; OK </code></pre> <p>Set master mode and check it:</p> <pre><code>AT+ROLE=1 &gt; OK AT+ROLE? &gt; +ROLE:1 &gt; OK </code></pre> <p>Reset and initialize (reset aborts, e.g. the inquiring state - quickly flashing LED; without initializing you would get ERROR(16)):</p> <pre><code>AT+RESET &gt; OK AT+INIT &gt; OK </code></pre> <p>Now the LED should slowly flash. Optionally: set password of the target device:</p> <pre><code>AT+PSWD=1234 &gt; OK </code></pre> <p>Show count of all authenticated devices in pair list:</p> <pre><code>AT+ADCN? &gt; +ADCN:7 &gt; OK </code></pre> <p>If the value is larger than 0, delete all authenticated devices in pair list:</p> <pre><code>AT+RMAAD &gt; OK </code></pre> <p>Now pair with the desired device (the last 20 mean 20s):</p> <pre><code>AT+PAIR=12,34,567890,20 &gt; OK </code></pre> <p>The LED starts flashing one time with a longer pause. Set the desired device:</p> <pre><code>AT+BIND=12,34,567890 &gt; OK </code></pre> <p>Now link (e.g. when connecting to the ELM327; the PC will create another new port after having requested the password from the user):</p> <pre><code>AT+LINK=12,34,567890 &gt; OK </code></pre> <p>The LED starts flashing two times with a longer pause. After linking, it might be that either the HC-05 switches to data-mode or continues in command-mode (haven't found out when it does one or the other).</p> <p><strong>Command mode (auto connect)</strong></p> <p>Now switch off the HC-05 and keep the CMD-DAT-switch to CMD. Switch it on again. It should automatically connect to the previously connected device. To switch to the data mode, first disconnect...</p> <pre><code>AT+DISC &gt; +DISC:SUCCESS &gt; OK </code></pre> <p>... and reconnect.</p> <pre><code>AT+LINK=12,34,567890 &gt; OK </code></pre> <p>Now the connection seems to have switched to data mode.</p> <p><strong>Data Mode</strong></p> <p>Now switch off the HC-05 and move the CMD-DAT-switch to DAT. Turn on the HC-05. It automatically will try to connect to the previously connected device - the LED should flash two times with longer pause - and you don't have to mess with HC-05-AT commands any more.</p>
16955
|serial|
How to use serial.read a sentences and serial.print after that enter to new line
2015-10-18T14:44:15.583
<p>This is my code but it doesn't work. I don't no why . I hope someone can explain the problem. Tks</p> <pre><code>unsigned char InTransfer; char buffer; void setup() { Serial.begin(9600); } void loop() { /* when get the sentences and print it*/ while ( Serial.available()) { buffer=Serial.read(); Serial.write(buffer); InTransfer=1; // detect } /* After done enter one time */ if (Serial.available()==0) if(InTransfer==1){ Serial.println(""); InTransfer=0; } } </code></pre>
<p>Your code works perfectly, I don't see a problem with it. It's doing <em>exactly</em> what you're telling it to.</p> <p>The problem lies in a fundamental lack of understanding about how serial communications work on your part, so you are telling it to do the wrong thing. Until you fix that aspect no program you try and write in this way will be a success.</p> <p>You should start by learning how serial communication actually works. A good starting point is an article I wrote ages ago: <a href="http://hacking.majenko.co.uk/reading-serial-on-the-arduino" rel="nofollow">http://hacking.majenko.co.uk/reading-serial-on-the-arduino</a></p>
16960
|serial|gsm|arduino-galileo|
Communicating Arduino with Intel Galileo
2015-10-18T18:50:25.107
<p>I'm doing a project where I have few sensors on Arduino Uno. Now I am trying to send some data to the internet where i figured using my GSM shield with the Galileo board I have is the best solution.</p> <p>The problem I am facing is that software serial is not working on Galileo so I have to use the Serial1 of Galileo board (Pin 0 and Pin 1) and I am out of serial ports. I was thinking of using serial communication between Arduino and Galileo but Galileo seems to have only pin0 and pin1 as serial and they are occupied by the GSM shield.</p> <p>Is there any part I am getting wrong or any suggestions?</p> <p>(other than using the sensors on Galileo and getting rid of the Arduino Uno :) )</p>
<p>You could use SPI/I2C as interface between Arduino and Galileo. They are better than plain serial.</p>
16961
|arduino-mega|relay|pull-up|
Relay module and internal pull-up resistors
2015-10-18T19:43:02.007
<p>I'm currently assembling a prototype of the lightning infrastructure (<em>based on several MEGAs interconnected via RS485, as described <a href="https://arduino.stackexchange.com/questions/15834/how-to-interconnect-multiple-arduinos-with-a-rpi-to-control-home-lights-switches">in this other post</a></em>) </p> <p>The prototype consists of three MEGAs, a couple of <a href="http://www.vimar.com/en/int/catalog/product/index/code/14008" rel="nofollow noreferrer">wall-push-button</a> and the two relay modules here below:</p> <ul> <li><a href="http://www.aliexpress.com/item/NEW-250V-2A-8-Channel-OMRON-SSR-G3MB-202P-Solid-State-Relay-Module-For-Arduino/32393847675.html" rel="nofollow noreferrer">250V 2A 8 Channel OMRON SSR G3MB-202P Solid State Relay Module For Arduino</a></li> <li><a href="http://www.aliexpress.com/item/5V-4-CH-OMRON-SSR-G3MB-202P-Solid-Relay-Module-with-Resistive-Fuse-For-Arduino/32419548955.html" rel="nofollow noreferrer">5V 4 CH OMRON SSR G3MB-202P Solid Relay Module with Resistive Fuse For Arduino</a></li> </ul> <p>Obviously I've:</p> <ul> <li>connected one endpoint of each push-buttons to Arduino INPUT-PIN; the other endpoint to ground;</li> <li>connected the relay-module control-pins to Arduino OUTPUT-PIN (and ensuring a properly connected ground).</li> <li>connected lamps to relay-modules power connectors.</li> </ul> <p>My question relates to "<strong>pull-up resistor</strong>": I've read in <strong>lots</strong> of places that when involving push-buttons, "pull-up resistors" are needed in order to prevent shorts between ground and input-pin. As such, there are <strong>lots</strong> of tutorial/videos on the web, showing a nice resistor added in the push-button circuit.</p> <p>Further investigating, I've also learnt from the official documentation that "<a href="https://www.arduino.cc/en/Tutorial/DigitalPins" rel="nofollow noreferrer"><em>...There are 20K pullup resistors built into the Atmega chip that can be accessed from software....</em></a>", by setting the <code>pinMode()</code> as <code>INPUT_PULLUP</code> or setting it to <code>INPUT</code> and the forcing a <code>digitalWrite(&lt;PIN&gt;,HIGH)</code>.</p> <p>So, I ended:</p> <ul> <li>directly connecting the two relay-modules to MEGAs INPUT-PINs and...</li> <li>...activating the internal pull-up, with <code>digitalWrite(&lt;INPUT_PIN&gt;,HIGH)</code>;</li> </ul> <p>Nothing more.</p> <p>This is the second evening I'm "testing" my Arduino-luggage-prototype and... lamps are turning on/off like a charm, without any noticeable problem.</p> <p>The question is: am I doing something nasty toward my MEGAs? Is the approach depicted above, a commonly-safe (as for the Arduino's health) approach?</p> <hr> <p>P.S.: should you wonder about how the prototype looks like, here is a photo (actually, taken right after the first power-up ;-)</p> <p><a href="https://i.stack.imgur.com/IWbOC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IWbOC.png" alt="enter image description here"></a></p>
<p>I am making the assumption the push buttons are wired directly to the mega. This may work but for me it is not acceptable. Why? All of those wires act as an antenna array tuned to a lot of different frequencies. My favorite trick is to use a 74C14 Schmidt trigger chip. The reason is several fold. First it isolates the antennas from the processor. The family I use will tolerate about 25volts input, giving a lot of head room. Second it makes the software a bit easier, all switches come in positive true. Third I use a low pass network in front so if one of the mains hits it it will probably survive. What I do is Pull up with a resistor that will cause about 1.5 ma to flow through the switch. This value is dependent on your voltage, I typically use 12 or 24 VDC. This input then goes through a 100K resistor to the input of the gate where I also put a .01 uF cap.</p> <p>I am also working on a similar project, I made the same decision on a hardwired network about 15 years ago. All the switching is on several output boards (5V) located in a PC AT. I also chose the mega for several reasons, first I needed full duplex with my network, the MAX485 will do that you just have to leave the receive enabled and cycle the transmit when you want to send something. I also added a low pass on the (A line I Think) to another pin so I could determine if the network was busy, I currently have about 150 outputs with very few inputs. Code is all in ASM86.</p> <p>I hope this helps, I will see if I can add to your reference question.</p> <p>Thanks, Gil</p>
16985
|arduino-uno|programming|c++|arduino-ide|
A whole basic game project Arduino
2015-10-19T02:54:52.490
<p>Firstly, I know that I have already posted this. I do not think anyone here is stupid so: The game is: a power source connected to 6 buttons connected to 6 LEDs. you press them all in the randomly generated order, and they blink in the order pressed after completion, then randomize and reset.</p> <p>I have an array shuffler code 1)Does the array shuffler work 2)How do I configure ports and attach them to values in the array, 3) How do I use an if-then statement to say if all buttons pressed in order, then LEDs blink 3 times? I have a picture but not the actual Arduino, so, upon request, I can post the picture. Thank you. code:</p> <pre><code>void setup() { // put your setup code here, to run once: } void loop() { // put your main code here, to run repeatedly: int questionNumberArray[] = {0,1,2,3,4,5,6};//the array itself const size_t n = sizeof(questionNumberArray) / //the array used sizeof(questionNumberArray[0]);//the base of the array for (size_t i = 0; i &lt; n - 1; i++) //the loop itself { size_t j = random(1, n - i); int t = questionNumberArray[i]; //integer output for increase questionNumberArray[i] = questionNumberArray[j];//the value definition questionNumberArray[j] = t; } } </code></pre> <p>The six buttons are connected to digital pins (1, 2, 9, 11, 12, 13)</p>
<p>So you leds are connected to "pins" not "ports." Since each of the buttons will turn on only 1 led we need to keep track of which button pairs with which led. To do this we can use a <code>struct</code> like this one:</p> <pre><code>struct ButtonLed{ int buttonPin; int ledPin; }; </code></pre> <p>You declare a <code>ButtonLed</code> like this: <code>ButtonLed button1 = {1, 0}</code> where the first parameter is the button's pin and the second is the led's pin. <strong>(All of the led pins are set to 0 since I don't know which pins you have them connected to.)</strong></p> <p>And the array will hold the button/led pin pair like this: </p> <p><code>ButtonLed questionNumberArray[] = {button1, button2, button3, button4, button5, button6};</code></p> <p>Since there are 6 leds you know that your array is size 6 so use this declaration instead </p> <p><code>const int n = 6;</code> </p> <p>I fixed you range for the random number generation. Look at the documentation for <code>random()</code> here <a href="https://www.arduino.cc/en/Reference/Random" rel="nofollow noreferrer">https://www.arduino.cc/en/Reference/Random</a>. We can use this function for shuffling the array. </p> <pre><code>void shuffleArray (ButtonLed arr [], const int size){ for (int i = 0; i &lt; size - 1; i++){ // iterates through array except last element int j = random(0, size); // generates a random index from (0 to n-1) inclusive // swap current index with random index ButtonLed t = arr[i]; arr[i] = arr[j]; arr[j] = t; } } </code></pre> <p>We will use this function to wait until the user enters a sequence of button presses:</p> <pre><code>ButtonLed getButtonPress (ButtonLed arr [], const int size){ bool pressed = false; ButtonLed pressedButton; while (!pressed){ // loops until a button was pressed for (int i = 0; i &lt; size &amp;&amp; !pressed; i++){ // !pressed allows early out if (digitalRead(arr[i].buttonPin)){ // one of the six buttons was pressed pressed = true; // exit both loops pressedButton = arr[i]; // stores which button was pressed } } } return pressedButton; // return the pressed button } </code></pre> <p>Essentially it gets stuck in a loop and reads each of the 6 buttons until one of them is pressed and then records which one was pressed.</p> <p>Try using the code below and read the comments the only thing you need to do is change all the zeros in the <code>ButtonLed</code> declarations to whatever pin the leds are connected to. Also the <code>struct</code> above needs to go into it's only file called "ButtonLed.h" It <strong>must</strong> be called that. </p> <pre><code>#include "ButtonLed.h" // These are ButtonLeds our newly created data type // they hold both an led's pin and the pin for the button // that turns it on ButtonLed button1 = {1, 10}; ButtonLed button2 = {2, 8}; ButtonLed button3 = {9, 7}; ButtonLed button4 = {11, 6}; ButtonLed button5 = {12, 5}; ButtonLed button6 = {13, 4}; // This function will randomly shuffle an array of ButtonLeds void shuffleArray (ButtonLed arr [], const int size){ for (int i = 0; i &lt; size - 1; i++){ // iterates through array except last element int j = random(0, size); // generates a random index from (0 to size-1) inclusive // swap current index with random index ButtonLed t = arr[i]; arr[i] = arr[j]; arr[j] = t; } } ButtonLed getButtonPress (ButtonLed arr [], const int size){ bool pressed = false; ButtonLed pressedButton; while (!pressed){ // loops until a button was pressed for (int i = 0; i &lt; size &amp;&amp; !pressed; i++){ // !pressed allows early out if (digitalRead(arr[i].buttonPin)){ // one of the six buttons was pressed digitalWrite(digitalRead(arr[i].ledPin, HIGH); // turns on the led the user chose delay(200); digitalWrite(digitalRead(arr[i].ledPin, LOW); // turns it back off pressed = true; // exit both loops pressedButton = arr[i]; // stores which button was pressed } } } return pressedButton; // return the pressed button } void setup() { randomSeed(analogRead(A0)); // This is how you set up the leds for output pinMode(button1.ledPin, OUTPUT); pinMode(button2.ledPin, OUTPUT); pinMode(button3.ledPin, OUTPUT); pinMode(button4.ledPin, OUTPUT); pinMode(button5.ledPin, OUTPUT); pinMode(button6.ledPin, OUTPUT); // This is how you set up the buttons for input pinMode(button1.buttonPin, INPUT); pinMode(button2.buttonPin, INPUT); pinMode(button3.buttonPin, INPUT); pinMode(button4.buttonPin, INPUT); pinMode(button5.buttonPin, INPUT); pinMode(button6.buttonPin, INPUT); } void loop() { // This array is of type ButtonLed our newly created data type ButtonLed questionNumberArray[] = {button1, button2, button3, button4, button5, button6}; const size_t n = 6; // array's size shuffleArray(questionNumberArray, n); numLeds = 1; bool guessCorrectly = false; // this while loop allows the user to keep trying until they get it right while (!guessCorrectly){ // This loop displays the correct sequence to the user for (int i = 0; i &lt; numLeds; i++){ digitalWrite(questionNumberArray[i].ledPin, HIGH); // turn on the led delay(500); // decrease this number to flash faster; increase to flash slower digitalWrite(questionNumberArray[i].ledPin, LOW); // turn off the led } bool correctButton = true; // the user has pressed the correct button ButtonLed userSequence [6]; // stores the sequence the user entered // lets the user push 6 buttons for (int i = 0; i &lt; numLeds; i++){ userSequence[i] = getButtonPress(questionNumberArray, numLeds); delay(500); // delay between button presses } // check if the user entered the correct sequence for (int i = 0; i &lt; numLeds &amp;&amp; correctButton; i++){ if (userSequence[i].buttonPin != questionNumberArray[i].buttonPin) correctButton = false; } if (correctButton){ // user entered the correct sequence guessCorrectly = true; // This will turn on the leds in the correct sequence for (int i = 0; i &lt; numLeds; i++){ digitalWrite(questionNumberArray[i].ledPin, HIGH); // turn on the led delay(500); // delay half a second digitalWrite(questionNumberArray[i].ledPin, LOW); // turn off the led } numLeds++; if (numLeds &gt; 6) --numLeds; } } } </code></pre> <p>After you are finished typing the code above it <code>ctrl+shift+n</code> and open a new tab called "ButtonLed.h" and add this to it:</p> <pre><code>#ifndef BUTTONLED_H #define BUTTONLED_H #include &lt;Arduino.h&gt; // We create new data type called ButtonLed which stores the button's pin // and the led's pin; this allows us to keep both an led and it's // corresponding button together without have to manage 2 arrays struct ButtonLed{ int buttonPin; int ledPin; }; #endif </code></pre> <p>Make sure you open a new tab and not a new project. Also as others have said you should really learn how to program. Be aware this code compiles however, I haven't tested it. I will update the code when you tell me what pins the leds are connected to.</p> <p><strong>Edit 1</strong></p> <p>I added a while loop that allows the user to keep trying until they guess correctly.</p> <p><strong>Edit 2</strong></p> <p>I also updated the code for which pins the leds are connected to. Remember they're connected to "pins" <strong>Not</strong> "ports.</p> <p><a href="https://i.stack.imgur.com/OMnho.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OMnho.png" alt="Schematic for your project."></a></p>
16988
|arduino-uno|
How to Store the Value of A Sr04 Ultrasonic distance sensor (ping)?
2015-10-19T04:26:07.320
<p>I am using a Sr04 Ultrasonic distance sensor with Uno clone for making a Alarm. The basic idea behind this project is that In Setup, Read the distance And store it in a varibale as Threshold. And in Loop, Check the distance readings regularly and if the Reading anytime is not equal to The threshold (that means someone interrupted in front of ultrasonic sensor), then a led flashes. I Know that is system is not enough good because the real world is a bit noisy. My problem is I am storing the theshold distance in "int" variable. The compiling error is "Cant convert Long Unsigned char to Int" something like this. Please tell me how can I store the reading of my sr04 sensor in a variable. I am using NewPing Library. </p>
<ol> <li>First you must verify that storing the value as int is even possible: long int can represent much larger values than int. Are you 100% sure that the maximum reading you will ever get can be represented as int?</li> <li>In case the answer to the previous question is "yes", then you can just cast it on the fly: <code>int int_val = (int)function_returning_longint();</code></li> <li>In case the answer is "no", you can either give up the idea of using int and stick with long, which is not necessarily bad, or you can scale down the value, at the price of loosing some resolution: <code>int int_val = function_returning_longint() &gt;&gt; 8;</code> This assumes that long is 16 bit and int is 8 bit, but it would be preferable to use explicit types, like <code>int8_t</code> and <code>int16_t</code>. And in your case you might have to shift by a different value than 8.</li> </ol> <p>Either way, do not make casts of from big type to small type without being 100% sure that the max value you will ever deal with can fit in the small type.</p>
16999
|mpu6050|gyroscope|
What's the difference between pow and sqrt in this code?
2015-10-19T10:40:29.123
<p>I'm not the best at Arduino so I'm sorry for my "noobiness".</p> <p>I'm extending some code that I found online to work on the gyroscope that I'm building.</p> <p>I'm wondering what the difference is between <code>pow</code> and <code>sqrt</code> in this code.</p> <p>I'm also wondering what the <code>180/pi</code> is used for. I haven't gotten my mind around this part yet.</p> <pre><code>arx = (180/3.141592) * atan(ax / pow((ay, 2) + pow(az, 2)); </code></pre> <p>What's the difference here?</p> <pre><code>ary = (180/3.141592) * atan(ay / sqrt(square(ax, 2) + square(az, 2))); </code></pre>
<p>Converting Gerben's comment into an answer:</p> <hr /> <p>pow(x, 2) is the second power, in other words:</p> <p><a href="https://i.stack.imgur.com/FxSj7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FxSj7.png" alt="x squared" /></a></p> <hr /> <p>sqrt(x) is the square root of x, that is:</p> <p><a href="https://i.stack.imgur.com/LrrbS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LrrbS.png" alt="Square root of x" /></a></p> <hr /> <p>A whole circle is 360 degrees or 2π when measuring in radians. So this ratio of <code>180 / 3.141592</code> is used to convert an angle in radians to an angle in degrees.</p> <p><a href="https://i.stack.imgur.com/q7Zfk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/q7Zfk.png" alt="radians to degrees" /></a></p>
17008
|arduino-uno|programming|c|interrupt|
Issue with leOS2 for one-time tasks
2015-10-19T17:33:02.940
<p>I'm trying to use the last version of <strong>leOS2 scheduler from Leonardo Miliani</strong> ( <a href="https://github.com/leomil72/leOS2" rel="nofollow">https://github.com/leomil72/leOS2</a> ) but I have a strange behavior with a very simplistic ONETIME task.</p> <p>Platform : Arduino Uno clone, so Atmel Atmega 328P CPU.</p> <p>My code is very straightforward : </p> <pre><code>#include "leOS2.h" leOS2 myOS; //create a new istance of the class leOS bool test = true; void setup() { myOS.begin(); //initialize the scheduler } void loop() { // Do some stuff ... if(test) { DoAndUndo(3000); test = false; } } void DoAndUndo(unsigned long duration) { doSomething(); myOS.addTask(cancelTheThing, myOS.convertMs(duration), ONETIME); } void doSomething() { Serial.println("thing on"); } void cancelTheThing() { Serial.println("thing is off"); } </code></pre> <p>In case it can be some kind of conflict, my code also relies on the following : </p> <pre><code>#include &lt;Wire.h&gt; #include &lt;LiquidCrystal_I2C.h&gt; #include &lt;IRremote.h&gt; </code></pre> <p>The problem is : myOS.addTask(cancelTheThing, myOS.convertMs(duration), ONETIME); is supposed to call asynchronously the "cancelTheThing" method 3 seconds later, and for only one time, and then forget it. But for an unknown reason, it's called after the expected delay, <strong>but it loops infinitely on this method</strong> ! In the example case above, my serial stream is filled with a lot of "thing is off" messages, and the µc is unresponsive to anything apart a reset.</p> <p>The call to DoAndUndo() will produce a such like output : </p> <pre><code> thing on </code></pre> <p>And 3s later, in a very fast infinite loop :</p> <pre><code> thing is off thing is off thing is off thing is off </code></pre> <p>If I remove the "ONETIME" flag, the task is called every three seconds (exactly as it's suppose to do, so the scheduler works, but it's not what I want in my use case).</p> <p>note : As a try of workaround, I've tried some tricks like calling haltScheduler() inside my cancelTheThing() and reenable it with restartScheduler() in DoAndUndo(), and also tried to call removeTask once it has ran, but it didn't help.</p> <p>Thank you for your help</p>
<p>There appears to be a fault with the library whereby if the only registered task is a one-shot task it doesn't get cancelled when it has executed.</p> <p>Adding another periodic task in <code>setup()</code> (say to blink an LED every 500ms) so there are now 2 tasks instead of one works around the problem.</p> <p>The way the system is written it will always try an execute task number 0 even when there are 0 tasks registered because they erroneously used a "do {...} while" construct instead of a "while { ...}" construct.</p> <hr> <p>I have filed a bug report, corrected the error, and raised a pull request with the fix in it. Until it gets accepted you can obtain the fixed version here: <a href="https://github.com/majenkotech/leOS2" rel="nofollow">https://github.com/majenkotech/leOS2</a></p>
17011
|arduino-uno|gsm|
Error while compiling
2015-10-19T18:30:07.353
<p>I made a code which can send the message to the entered phone number while it receieves a specific message or when the push button is pressed. but it is showing the error that 'smsReceivingFunction' was not declared in this scope. I'm a beginner and don't know what i'm doing wrong.</p> <p>to know the working of functions of library-- <a href="http://1sheeld.com/docs/sms/#example" rel="nofollow">http://1sheeld.com/docs/sms/#example</a></p> <p>here is the code--</p> <pre><code>#include &lt;OneSheeld.h&gt; float lat ; float lon ; char charlat [30]; char charlon [30]; char readings [150]; int buttonPin=11; int ledPin=12; void setup() { // put your setup code here, to run once: OneSheeld.begin(); /* Set the button pin as input. */ pinMode(buttonPin,INPUT); /* Set the LED pin as output. */ pinMode(ledPin,OUTPUT); SMS.setOnSmsReceive(&amp;smsReceivingFunction); } void loop() { charlat[0] = 0; charlon[0] = 0; readings [0] = 0; if(digitalRead(buttonPin) == HIGH) { /* Turn on the LED. */ digitalWrite(ledPin,HIGH); delay( 1000); digitalWrite(ledPin,HIGH); delay( 500); lat = GPS.getLatitude(); lon = GPS.getLongitude(); dtostrf(lat, 3, 7, charlat); dtostrf(lon, 3, 7, charlon); strcat(readings, "please call me I i do not pick up the call please reach to my location:\n"); strcat(readings, "http://maps.google.com/maps?q="); strcat (readings, charlat); strcat(readings, ","); strcat (readings, charlon); SMS.send("+917771914436", readings); void smsReceivingFunction(const char * number,const char * text); if(!strcmp(number,"+7771914436")) /* phone number from which you will send the sms "PUT YOURS IN PLACE OF +1234567890" */ { if(!strcmp(text,"?")) lat = GPS.getLatitude(); lon = GPS.getLongitude(); dtostrf(lat, 3, 7, charlat); dtostrf(lon, 3, 7, charlon); strcat(readings, "please call me I i do not pick up the call please reach to my location:\n"); strcat(readings, "http://maps.google.com/maps?q="); strcat (readings, charlat); strcat(readings, ","); strcat (readings, charlon); SMS.send("+917771914436", readings); } } } } </code></pre>
<p>Basically the formatting and layout of your program is completely wrong. You haven't actually defined this <code>smsReceivingFunction</code> anywhere. You have created a <em>prototype</em> to it part way through your <code>loop()</code> function, but not created the actual function.</p> <p>You should learn to strictly indent your program properly. It is important, since by doing so you can follow the flow and structure of your program much easier.</p> <p>For instance, if I pass your program through <a href="http://astyle.sourceforge.net/" rel="nofollow">Artistic Style</a> to attempt to automatically correct your indenting it results in this:</p> <pre><code>#include &lt;OneSheeld.h&gt; float lat ; float lon ; char charlat [30]; char charlon [30]; char readings [150]; int buttonPin = 11; int ledPin = 12; void setup() { // put your setup code here, to run once: OneSheeld.begin(); /* Set the button pin as input. */ pinMode(buttonPin, INPUT); /* Set the LED pin as output. */ pinMode(ledPin, OUTPUT); SMS.setOnSmsReceive(&amp;smsReceivingFunction); } void loop() { charlat[0] = 0; charlon[0] = 0; readings [0] = 0; if (digitalRead(buttonPin) == HIGH) { /* Turn on the LED. */ digitalWrite(ledPin, HIGH); delay( 1000); digitalWrite(ledPin, HIGH); delay( 500); lat = GPS.getLatitude(); lon = GPS.getLongitude(); dtostrf(lat, 3, 7, charlat); dtostrf(lon, 3, 7, charlon); strcat(readings, "please call me I i do not pick up the call please reach to my location:\n"); strcat(readings, "http://maps.google.com/maps?q="); strcat (readings, charlat); strcat(readings, ","); strcat (readings, charlon); SMS.send("+917771914436", readings); void smsReceivingFunction(const char * number, const char * text); if (!strcmp(number, "+7771914436")) { /* phone number from which you will send the sms "PUT YOURS IN PLACE OF +1234567890" */ if (!strcmp(text, "?")) { lat = GPS.getLatitude(); } lon = GPS.getLongitude(); dtostrf(lat, 3, 7, charlat); dtostrf(lon, 3, 7, charlon); strcat(readings, "please call me I i do not pick up the call please reach to my location:\n"); strcat(readings, "http://maps.google.com/maps?q="); strcat (readings, charlat); strcat(readings, ","); strcat (readings, charlon); SMS.send("+917771914436", readings); } } } } </code></pre> <p>As you can now see you have an extra <code>}</code> at the end of your sketch, so your brackets are not balanced. That in itself is a syntax error. Also you can see your function prototype slap bang in the middle of your loop() function:</p> <pre><code>... SMS.send("+917771914436", readings); void smsReceivingFunction(const char * number, const char * text); if (!strcmp(number, "+7771914436")) { /* phone number ... </code></pre> <p>I think, though of course I can't actually test this since I don't have your hardware, that you really meant to start a new function at that point in your program, and of course that would mean finishing the previous function first: you <em>cannot</em> nest functions inside each other. So I would guess your program <em>should</em> have looked something more like this:</p> <pre><code>#include &lt;OneSheeld.h&gt; float lat ; float lon ; char charlat [30]; char charlon [30]; char readings [150]; int buttonPin = 11; int ledPin = 12; void setup() { // put your setup code here, to run once: OneSheeld.begin(); /* Set the button pin as input. */ pinMode(buttonPin, INPUT); /* Set the LED pin as output. */ pinMode(ledPin, OUTPUT); SMS.setOnSmsReceive(&amp;smsReceivingFunction); } void loop() { charlat[0] = 0; charlon[0] = 0; readings [0] = 0; if (digitalRead(buttonPin) == HIGH) { /* Turn on the LED. */ digitalWrite(ledPin, HIGH); delay( 1000); digitalWrite(ledPin, HIGH); delay( 500); lat = GPS.getLatitude(); lon = GPS.getLongitude(); dtostrf(lat, 3, 7, charlat); dtostrf(lon, 3, 7, charlon); strcat(readings, "please call me I i do not pick up the call please reach to my location:\n"); strcat(readings, "http://maps.google.com/maps?q="); strcat (readings, charlat); strcat(readings, ","); strcat (readings, charlon); SMS.send("+917771914436", readings); } } void smsReceivingFunction(const char * number, const char * text) { if (!strcmp(number, "+7771914436")) { /* phone number from which you will send the sms "PUT YOURS IN PLACE OF +1234567890" */ if (!strcmp(text, "?")) { lat = GPS.getLatitude(); } lon = GPS.getLongitude(); dtostrf(lat, 3, 7, charlat); dtostrf(lon, 3, 7, charlon); strcat(readings, "please call me I i do not pick up the call please reach to my location:\n"); strcat(readings, "http://maps.google.com/maps?q="); strcat (readings, charlat); strcat(readings, ","); strcat (readings, charlon); SMS.send("+917771914436", readings); } } </code></pre>
17014
|programming|c++|
Using random() in a header file
2015-10-19T22:46:33.207
<pre><code>#ifndef FOO_H #define FOO_H struct Foo{ int randInt = random(0, 101); }; #endif </code></pre> <p>I have a header file with a <code>struct</code> like above but when I compile I get this error: </p> <p><code>'random' was not declared in this scope</code></p> <p>How can I use random() in a header file?</p>
<p>Add <code>#include &lt;Arduino.h&gt;</code> like this</p> <pre><code>#ifndef FOO_H #define FOO_H #include &lt;Arduino.h&gt; struct Foo{ int randInt = random(0, 101); }; #endif </code></pre>
17021
|arduino-uno|c++|communication|softwareserial|rf|
Unable to tell if error is from receiving or transmitting end
2015-10-20T06:37:19.180
<p>so I am having trouble sending data using software serial's write function. </p> <p>TX Code:</p> <pre><code>#include &lt;SoftwareSerial.h&gt; SoftwareSerial TX(2,3); void setup() { // put your setup code here, to run once: TX.begin(1200); } void loop() { TX.write(60); } </code></pre> <p><strong>Is the delay necessary?</strong></p> <p>RX Code: </p> <pre><code>#include &lt;SoftwareSerial.h&gt; SoftwareSerial RX(2,3); //(rx pin, tx pin) const unsigned int bufferSize = 100; void setup() { Serial.begin(9600); RX.begin(1200); } void printBuffer(const uint8_t *serialBuffer) { //print contents of buffer for (int i = 0; i&lt;100; i++) Serial.println(serialBuffer[i], BIN); } void processBytes(const uint8_t value) { static uint8_t serialBuffer[bufferSize]; //buffer to hold values static unsigned int startPosition=0; if(startPosition &lt; bufferSize) serialBuffer[startPosition++] = value; else { printBuffer(serialBuffer); startPosition = 0; } }//end of processBytes void loop() { //check if data is available in serial buffer while(RX.available()) { //process data processBytes(RX.read()); } } </code></pre> <p>If i transmit the number 60, it prints 226 constantly for 2-3 seconds, then prints 60 for a short while, then goes back to printing 226. Am I doing something wrong with my code? </p> <p><strong>FIRST QUESTION:</strong> In the case when startPosition (in the process function) equals 100, it will call print. Print will then print 100 integers. Now, when doing that, there could still be data being transmitted from the transmitter. But the read function won't be executed until printBuffer returns, process returns, and the while loop iterates again. So during that time, couldn't some transmitted values potentially not be read? </p> <p><strong>SECOND QUESTION</strong> How come Software serial doesn't synchronize incorrectly more often? How is it being so accurate if the start bit is just a single bit and it's a 0. So for instance, if payload has some 0s, how come one of those 0s aren't being assumed to be the startbit? How does this get resolved? I looked at the software serial library, but I am not able to find out why. Any guidance here?</p> <p><strong>THIRD QUESTION</strong> Other than getting the startbit syncing right, are there other ways to sync the data? I was reading of NRZ encoding, manchester encoding, etc. Can any of these be implemented here? Also, would it be wise to alter the softwareSerial library to have more than one startbit? </p> <p>Any guidance would be very appreciated! Thank you so much! This is all being done with wireless RF modules. </p>
<pre class="lang-C++ prettyprint-override"><code>void loop() { Serial.println("NEW-------------"); int x; int y[100]; for(int i = 0; i&lt;100; i++){ x=RX.read(); y[i] = x; } ... } </code></pre> <p>You are reading data without checking if there is any data there. That's like watching the TV without checking if it is turned on. Of course you get weird data.</p> <hr> <pre class="lang-C++ prettyprint-override"><code>SoftwareSerial RX(0,1); //(rx pin, tx pin) </code></pre> <p>Pins 0 and 1 are used by HardwareSerial. Why are you using them for SoftwareSerial?</p> <hr> <pre class="lang-C++ prettyprint-override"><code>SoftwareSerial RX(0,1); //(rx pin, tx pin) ... Serial.begin(9600); RX.begin(1200); </code></pre> <p>So you initialized HardwareSerial, which now controls pins 0 and 1.</p> <p>Then you try to initialize SoftwareSerial on those <strong>same</strong> pins! Would you mind explaining why?</p> <p>Whatever your explanation is, it won't work.</p> <hr> <blockquote> <p>I've added in the changes you mentioned, but the data still seems to be skewed.</p> </blockquote> <p>You've changed things, for sure:</p> <pre class="lang-C++ prettyprint-override"><code> for(int i = 0; i&lt;100; i++){ if(RX.available()) x=RX.read(); y[i] = x; } </code></pre> <p>Let's see. In a loop of 100 iterations you see if anything is available (and if so, put it into <code>x</code>).</p> <p>Then, regardless of <strong>whether or not you got anything</strong> you now assign <code>x</code> to <code>y[i]</code>. So, most of the time, <code>y[i]</code> will have garbage in it.</p> <blockquote> <p>the data still seems to be skewed</p> </blockquote> <p>Not surprised. Do it differently. Only write to the array if you have data. In fact you may want a complete rework. Read this:</p> <p><a href="http://www.gammon.com.au/serial" rel="nofollow">How to read serial without blocking</a></p> <hr> <blockquote> <p>I have posted the amended code. Change: Only add to the array is data is being read from buffer.</p> </blockquote> <pre class="lang-C++ prettyprint-override"><code> int y[100]; for(int i = 0; i&lt;100; i++){ if(RX.available()) { x=RX.read(); y[i] = x; } } for (int j = 1; j&lt;=64; j++){ Serial.println(y[j]); } </code></pre> <p>You still have not fixed it. Let me talk you through what it is doing now.</p> <p>You are making 100 attempts to read some data. One or two may succeed, and they will be put into the buffer <code>y</code> (funny name for a buffer, right?).</p> <p>So imagine <code>.</code> is garbage and <code>X</code> is good data, after doing that loop of 100 the buffer will look like this:</p> <pre class="lang-C++ prettyprint-override"><code>........X...........X...........X...X......................X............................................. </code></pre> <p>So your buffer is still 80% unchanged garbage. Then you print the first 64 elements (why 64 and not 100?) and you get a lot of garbage out. Exactly as expected.</p> <hr> <p>You need to think about what you are doing. Draw it out on a bit of paper, perhaps.</p> <p>Here is some example code from the page I linked for you, more than once. Please compare:</p> <pre class="lang-C++ prettyprint-override"><code>// how much serial data we expect before a newline const unsigned int MAX_INPUT = 50; void setup () { Serial.begin (115200); } // end of setup // here to process incoming serial data after a terminator received void process_data (const char * data) { // for now just display it // (but you could compare it to some value, convert to an integer, etc.) Serial.println (data); } // end of process_data void processIncomingByte (const byte inByte) { static char input_line [MAX_INPUT]; static unsigned int input_pos = 0; switch (inByte) { case '\n': // end of text input_line [input_pos] = 0; // terminating null byte // terminator reached! process input_line here ... process_data (input_line); // reset buffer for next time input_pos = 0; break; case '\r': // discard carriage return break; default: // keep adding if not full ... allow for terminating null byte if (input_pos &lt; (MAX_INPUT - 1)) input_line [input_pos++] = inByte; break; } // end of switch } // end of processIncomingByte void loop() { // if serial data available, process it while (Serial.available () &gt; 0) processIncomingByte (Serial.read ()); // do other stuff here like testing digital input (button presses) ... } // end of loop </code></pre>
17022
|arduino-uno|relay|safety|
Reasons why it is not OK to connect a relay directly from an Arduino digital pin
2015-10-20T07:46:43.553
<p>After looking into various schematics on controlling a relay via an Arduino, I have noticed that, most of the time, transistors are used to switch the separate supply into the relay coil rather than directly supplying the relay with the 5-Volt output from the I/O pin of the Arduino. For example, I have a 5-volt DPDT relay and also a small dc motor. I want to drive both directly from my Arduino UNO (SMD clone) with an Atmel328 processor? Would it be advisable to proceed?</p> <p>If not (most likely):</p> <ol> <li><p>Can someone give a detailed explanation and might as well important cautions on current limits and stuff?</p></li> <li><p>How can one control such components without risking the Arduino? What are some common means to accomplish this?</p></li> <li><p>What other devices can generally harm an Arduino board (or any microcontroller unit) in a similar manner?</p></li> </ol> <p>I'm just a beginner who wants to be extremely cautious. Thanks.</p>
<p>Let us look as some basic's, these seem to be the basis of a lot of questions:</p> <p>A capacitor when power is switched on draws a huge amount of current that tapers off as it gets charged. This curve is also called the RC time constant (this is close but not exact &quot;<a href="http://www.electronics-tutorials.ws/rc/rc_1.html" rel="nofollow noreferrer">http://www.electronics-tutorials.ws/rc/rc_1.html</a>&quot; will give a better explanation).</p> <p>When switching off a capacitor discharges at an exponential rate (RC time constant) depending on the value, charge voltage and the load. This makes them good for holding power for a short time when the power fails.</p> <p>An Inductor draws nothing when first switched on but the current increases exponentially until its voltage reaches the supply voltage.</p> <p>When switched off the inductive field in the inductor collapse causing the polarity to reverse. The voltage will rise unlimited until typically something externally limits it. The faster it is turned off the quicker the rise time and voltage. Energy will cease to flow when the inductive charge is dissipated. Guess where this current goes when the inductive load such as a relay is connected to a port pin?</p> <p>For this reason you need to put a diode (commonly called a fly wheel diode) across the inductive load. Google for: &quot;inductor/capacitor charge curve&quot; you will find a lot of nice graphs explaining this. This diode is not necessary if you use an appropriately rated MOSFET (UIS). The UIS (Unclamped Inductive Spike) information is in the MOSFET data sheet. If you look at the circuit it has the cathode + connected to the most positive side of the power supply. In this configuration it will not conduct unless the voltage is reversed (when the inductive load is switched off).</p> <p>Another common misconception is you can load a microprocessor I/O to the maximum. This is bad design. They give you a maximum per pin, per port and for the chip. At room temperature you will probably get away with it for a while.</p> <p>Let us assume we have a port with a 40mA load. The output is 0.005 from the power rail. Using Ohm’s law we are dissipating 20 milliwatts of power on one pin. At this rate of loading it does not take long to over heat the device because of internal power dissipation.</p> <p>When the output pin is changing state it draws more current because it has to charge or discharge its internal and the external capacitance, ‘more heat’, more speed ‘more heat’.</p> <p>If you look some of the specs will give you a maximum temperature, it is for the junction on the die, not the case temperature. Plastic is a poor conductor so heat sinking the package does not do a lot. Now consider this along with the ambient temperature. The ratings are given typically with the device at 25C, guess what happens when it gets warmer.</p> <p>Have fun,</p> <p>Gil</p>
17029
|programming|c++|
Passing a static array to a function
2015-10-20T13:06:47.020
<p>I have a functon that creates a instance of <code>KeyReport</code> and I want to fill statically the <code>KeyReport.keys</code> array. I'm new in the Arduino world so I'll put a example to explain it better:</p> <pre><code>void sendKey(byte keys[6], byte modifiers) { KeyReport report = {0}; report.keys = keys; // This is my main trouble report.modifiers = modifiers; report.reserved = 1; Keyboard.sendReport(&amp;report); } void setup(){ delay(3000); sendKey( {0x17,0,0,0,0,0}, 0x5); // I want to send hardcoded reports like this } void loop(){} </code></pre>
<pre><code>report.keys = keys; // This is my main trouble </code></pre> <p>You can't assign the contents of one array to the contents of another array. You can only copy the contents manually from one to the other.</p> <p>The simplest way is with a loop:</p> <pre><code>for (int i = 0; i &lt; 6; i++) { report.keys[i] = keys[i]; } </code></pre> <p>There is a helper function - <code>memcpy()</code> - which can do it for you if you prefer:</p> <pre><code>memcpy(report.keys, keys, 6); </code></pre> <p>It effectively does exactly the same thing - copy 6 bytes starting from the address of <code>keys</code> into the addresses starting at <code>report.keys</code>.</p> <p>As for the "hard coded" reports I suggest you create some <code>const</code> arrays in the global context - and even use <code>PROGMEM</code> to ensure they consume no RAM. That, of course, requires an entirely different way of passing and accessing the data. It may be simpler to split the report into 6 individual variables and pass each byte separately:</p> <pre><code>void sendKey(byte k0, byte k1, byte k2, byte k3, byte k4, byte k5, byte modifiers) { KeyReport report = {0}; report.keys[0] = k0; report.keys[1] = k1; report.keys[2] = k2; report.keys[3] = k3; report.keys[4] = k4; report.keys[5] = k5; report.modifiers = modifiers; report.reserved = 1; Keyboard.sendReport(&amp;report); } sendKey(0x17, 0, 0, 0, 0, 0, 0x05); </code></pre> <p>Yes, it's a little more long winded in the function, but calling the function is somewhat more simplified over the other options.</p>
17033
|arduino-uno|led|lcd|
LED cube and 200 mA limitation
2015-10-20T14:27:04.767
<p>I'm new to electronics and have been getting rather into my Arduino. But I don't just like following an instructable to do something. I like to know the math behind it and how it works inside. Now from my understanding the Arduino (Uno R3 for me), has a 200 mA max current. The LEDs I used have a 20 mA current. Now with 64 LEDs, wouldn't this fry my Arduino? This also applies to my LCD screen with a 160 mA current. Am I missing a key secret to going over amperage?</p>
<p>I'm assuming you're talking about an 8x8x8 cube.</p> <p>The 200mA is for all IO. The regular 5v line can supply 500mA. Since you don't have 64 pins available, you are not supplying the leds via the Arduino directly. Probably using some shift register, or led driver chips for the 64 (cathode) columns. For the 8 levels you'd use some PNP transistors or P-channel mosfets.</p> <p>So the Arduino won't drive any led directly, so it will only use a few tens of milli-amps. Since you'll draw around 1.3A when all leds are lid, you should power the external components directly from the power supply, instead of via the Arduino. Or you'll hit the 500mA limit.</p> <p>So the Arduino is just pushing the levers, and not doing any of the hard work (crane analogy).</p>
17039
|arduino-uno|
Powering Arduino with 110v and controlling relay
2015-10-20T18:54:04.507
<p>I've found a lot of tutorials about how to use an Arduino to control power supplies to lamps and things like that using a relay. However, I also need to power the Arduino with the same power that is going through the relay. </p> <p>In other words, I'd like to be able to plug my device into the wall. The device would use the 110VAC to power the Arduino. My device would also have some outlets that I could plug something into. The Arduino would be connected to a relay and would decide when to enable electricity to the outlet. The important part being that I would like everything to be on one power source. </p> <p>Do I need to have a step down converter to transform the power, in addition to the relay? Is there some sort of break out board that has both of these functionalities in one board? What is the best way to do this?</p>
<p>In these cases where power must come from mains, my preferred solution is to buy a cheap phone charger+usb cable from ebay. They are sealed and safer than do-it-yourself solutions. The power adapter is barely larger than a normal plug for mains.</p> <p>If you absolutely need to reach the arduino with only one cable, you can still use the solution i gave, only use a power cord to reach the contraption, then use a socket expander for mains and very short usb cable.</p>
17042
|arduino-uno|esp8266|
Arduino WIFI compiler error
2015-10-20T21:01:58.627
<p>Just bought an ESP8266 module to try it using my arduino uno R3. I have connected my WIFI module correctly, anyways evenb if i disconnect it, the error occur.</p> <p>While trying to upload the WIFI (connect with wpa) sketch i get several errors.</p> <p>First i tried uploading the hole sketch, i got those errors:</p> <pre><code>/usr/share/arduino/libraries/WiFi/WiFi.cpp: In member function ‘uint8_t* WiFiClass::macAddress(uint8_t*)’: /usr/share/arduino/libraries/WiFi/WiFi.cpp:112:1: error: unable to find a register to spill in class ‘POINTER_REGS’ /usr/share/arduino/libraries/WiFi/WiFi.cpp:112:1: error: this is the insn: (insn 35 25 26 2 (set (reg:QI 23 r23) (mem/c:QI (plus:HI (reg/f:HI 28 r28) (const_int 2 [0x2])) [3 S1 A8])) /usr/share/arduino/libraries/WiFi/WiFi.cpp:110 28 {movqi_insn} (nil)) /usr/share/arduino/libraries/WiFi/WiFi.cpp:112: confused by earlier errors, bailing out </code></pre> <p>After that i tried to only import just the libraries and try to compile it. Even with this method i get errors</p> <p>Code</p> <pre><code>#include &lt;WiFiServer.h&gt; #include &lt;WiFiClient.h&gt; #include &lt;WiFi.h&gt; </code></pre> <p>error:</p> <pre><code>In file included from /usr/share/arduino/libraries/WiFi/WiFiServer.h:8:0, from sketch_oct20b.ino:1: /usr/share/arduino/hardware/arduino/cores/arduino/Server.h:4:29: error: expected class-name before ‘{’ token In file included from sketch_oct20b.ino:1:0: /usr/share/arduino/libraries/WiFi/WiFiServer.h:14:3: error: ‘uint16_t’ does not name a type /usr/share/arduino/libraries/WiFi/WiFiServer.h:17:22: error: field ‘uint16_t’ has incomplete type /usr/share/arduino/libraries/WiFi/WiFiServer.h:18:24: error: ‘uint8_t’ has not been declared /usr/share/arduino/libraries/WiFi/WiFiServer.h:20:11: error: ‘size_t’ does not name a type /usr/share/arduino/libraries/WiFi/WiFiServer.h:21:11: error: ‘size_t’ does not name a type /usr/share/arduino/libraries/WiFi/WiFiServer.h:22:3: error: ‘uint8_t’ does not name a type /usr/share/arduino/libraries/WiFi/WiFiServer.h:24:9: error: ‘Print’ has not been declared /usr/share/arduino/libraries/WiFi/WiFiServer.h:18:42: error: ‘NULL’ was not declared in this scope </code></pre> <p>I can just figure out some syntax errors, but my c is not good enough to understand much of it.</p> <p>Can anyone tell me what am i doing wrong and show me how it will be done?</p>
<p>The WiFi libraries (such as <code>Wifi.h</code>, <code>WifiClient.h</code>, and <code>WiFiServer.h</code>) are used for interfacing with the official Arduino WiFi shield. Interfacing with an ESP8266 module is typically done by issuing AT commands via UART (i.e. <code>Serial.write()</code>, etc.)</p>
17057
|usb|arduino-leonardo|keyboard|atmega32u4|
Keyboard.print() skips keys
2015-10-21T07:19:40.447
<p>I'm playing with the Arduino Leonardo <code>Keyboard.print()</code> command, but I'm facing a annoying problem: </p> <p>When I print a double quote, it will not appear and also will make to disappear the next character (i.e.):</p> <pre><code>Keyboard.print("echo \"This is a demo\""); </code></pre> <p>Output:</p> <pre><code>echo his is a demo </code></pre> <p>And when I use this line:</p> <pre><code>Keyboard.print("echo -This is \"a demo-"); </code></pre> <p>Output (note the umlaut over the <code>a</code> instead of getting <code>"a</code>):</p> <pre><code>echo 'This is ä demo' </code></pre> <p>I suspect that the problem is that my computer is configured to use Spanish layout. </p> <p>What source code file can I change to fix this? I can't find the defines used by <code>Keyboard.print()</code></p>
<p>In your particular case, the double quote <strong><em>is to be entered</em></strong> (using the <a href="https://docs.microsoft.com/en-us/globalization/keyboards/kbdsp.html" rel="nofollow noreferrer">Spanish keyboard layout</a>) by <kbd>Shift</kbd> + the physical key labelled <kbd>2</kbd>. On a <a href="https://en.wikipedia.org/wiki/File:KB_United_States-NoAltGr.svg" rel="nofollow noreferrer">US keyboard</a>, <kbd>Shift</kbd> + the physical key labelled <kbd>2</kbd> is "@".</p> <p>Thus, this simply will get the desired result (the Arduino library assumes a US keyboard layout):</p> <pre><code>Keyboard.print("echo @This is a demo@"); </code></pre> <h3>More general solution</h3> <p>More generally, strings can be encoded as in the following table (the exact mappings depend on the particular keyboard layout - this will work for many European keyboard layouts).</p> <p>If the <em>physical key</em> (and modifier key, if any) <em>exists</em> on <a href="https://en.wikipedia.org/wiki/File:KB_United_States-NoAltGr.svg" rel="nofollow noreferrer">the US keyboard</a> to get the character typed out using the non-US keyboard layout, then this method works fine.</p> <pre><code>To get Use Notes -------------------------------------------- ; &lt; Will result in Shift action : &gt; Will result in Shift action ( * Will result in Shift action ) ( Will result in Shift action / &amp; Will result in Shift action ? _ Will result in Shift action = ) Will result in Shift action &amp; ^ Will result in Shift action - / + - _ ? " @ Will result in Shift action , , The same . . The same # # The same </code></pre> <h3>Even more general solution</h3> <p>Even more generally, some keys are not on the US keyboard (e.g. the 102th key on European keyboards for the original PC keyboards, often with <kbd>&lt;</kbd>, <kbd>></kbd>, <kbd>\</kbd>, and <kbd>|</kbd>), and it is <strong><em>not</em></strong> possible to use <a href="https://www.arduino.cc/reference/en/language/functions/usb/keyboard/keyboardprint/" rel="nofollow noreferrer">Keyboard.print()</a>.</p> <p>Instead, use the low-level <a href="https://www.arduino.cc/en/Reference/HID" rel="nofollow noreferrer">HID().SendReport()</a> function - with <a href="https://www.usb.org/sites/default/files/documents/hut1_12v2.pdf#page=56" rel="nofollow noreferrer">code 100</a> (decimal) for the first parameter for the 102th key. See the library source code, Keyboard.cpp (/libraries/Keyboard/src/Keyboard.cpp), for how to use HID().SendReport().</p> <h3>Alternative solution</h3> <p>Some operating systems enable entering characters using the keyboard and a numeric code.</p> <p>This is at the expense of making it operating-system dependent (but making it independent of the active keyboard layout).</p> <p>For example, <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>U</kbd> <a href="https://askubuntu.com/questions/88347/how-can-i-type-ascii-characters-like-alt-numpad-in-windows">on Linux</a> (GUI only, dependent on the window manager(?)). For the particular problem (the Unicode code point for <code>"</code> is <em>0022</em>), without any functional abstraction to reduce the redundancy:</p> <pre><code>Keyboard.print("echo "); Keyboard.press(KEY_LEFT_CTRL); Keyboard.press(KEY_LEFT_SHIFT); Keyboard.press('u'); Keyboard.releaseAll(); Keyboard.print("0022"); Keyboard.press(KEY_RETURN); Keyboard.releaseAll(); Keyboard.print("This is a demo"); Keyboard.press(KEY_LEFT_CTRL); Keyboard.press(KEY_LEFT_SHIFT); Keyboard.press('u'); Keyboard.releaseAll(); Keyboard.print("0022"); Keyboard.press(KEY_RETURN); Keyboard.releaseAll(); </code></pre> <p>Unicode code points <a href="https://unicode-table.com/en/" rel="nofollow noreferrer">can be found at unicode-table.com</a>.</p> <h3>Media keys</h3> <p>Even though the media keys are listed in <a href="https://www.usb.org/sites/default/files/documents/hut1_12v2.pdf#page=56" rel="nofollow noreferrer">the table</a> (e.g. code 128 for "Volume Up" on page 53), they do not work using the method described in the previous section. But there is <a href="https://arduino.stackexchange.com/questions/8934/send-keyboard-media-keys-with-keyboard-library/75466#75466">a solution</a>.</p> <h3>Platform</h3> <p>This was tested with:</p> <ul> <li><a href="https://arduino.stackexchange.com/questions/8934/send-keyboard-media-keys-with-keyboard-library/75466#75466">Arduino Leonardo</a></li> <li>The Spanish keyboard layout was added to the Linux settings and activated. There were 14 different ones to choose from, but I used the one labelled "Spanish". It was verified that "@" actually resulted in an output of "<code>"</code>". It was also verified that the <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>U</kbd> method worked.</li> <li>Linux, <a href="https://en.wikipedia.org/wiki/Ubuntu_version_history#Ubuntu_19.10_(Eoan_Ermine)" rel="nofollow noreferrer">Ubuntu&nbsp;19.10</a> (Eoan Ermine), but with <a href="https://en.wikipedia.org/wiki/GNOME" rel="nofollow noreferrer">the buggy GNOME</a> replaced by <a href="https://en.wikipedia.org/wiki/Cinnamon_(desktop_environment)" rel="nofollow noreferrer">Cinnamon</a>.</li> <li>The Arduino Leonardo connected to an <em>extra current</em> port of a <a href="https://en.wikipedia.org/wiki/Ubuntu_version_history#Ubuntu_19.10_(Eoan_Ermine)" rel="nofollow noreferrer">D-Link</a> USB hub (necessary, for unknown reasons - probably a local problem)</li> <li>Arduino IDE v. 1.18.10</li> </ul>
17060
|arduino-uno|c++|i2c|string|struct|
I2C_Anything String / Char Array issues
2015-10-21T13:17:36.497
<p>I've been working with the lovely I2C_Anything.h (thanks to the great work and support from Nick over at <a href="http://www.gammon.com.au/forum/?id=10896&amp;reply=9#reply9" rel="nofollow">http://www.gammon.com.au/forum/?id=10896&amp;reply=9#reply9</a>).. All working great, I was using Serial communication between Teensy 3.1 &amp; mini pro but looking to replace with I2C - I was sending a file name across that was fine, but not managing to figure it out with the I2C_Anything technique.. here's some snippets:</p> <p><strong>MASTER</strong></p> <pre><code>const uint8_t MaxMP3Name = 13; //==================================== // DATA STRUCTURE FOR MP3 SLAVE //==================================== struct SEND_MP3_STRUCTURE{ char Filename[MaxMP3Name]; uint8_t VolLeft; uint8_t VolRight; uint8_t Command; }; SEND_MP3_STRUCTURE txMP3; #define MP3_SLAVE_ADDRESS 77 const uint8_t PlayFile = 1; const uint8_t PauseFile = 2; const uint8_t StopFile = 3; ... etc //#################################// //## SEND MP3 COMMAND ##// //#################################// void sendMP3Command(String MP3File, uint8_t Command) { char *TextArray[MaxMP3Name]; MP3File.toCharArray(TextArray, MaxMP3Name); txMP3.Filename = TextArray; txMP3.VolLeft = VolLeft; txMP3.VolRight = VolRight; txMP3.Command = Command; Wire.beginTransmission(MP3_SLAVE_ADDRESS); I2C_writeAnything(txMP3); Wire.endTransmission(true); } ...etc </code></pre> <p>... not entirely sure what i'm doing, I've tried most variations (using String in the struct vs char *Filename[] and various other attempts).</p> <p><strong>SLAVE</strong></p> <pre><code>const uint8_t MaxMP3Name = 13; //==================================== // RECEIVE DATA FORMAT //==================================== struct RECEIVE_DATA_STRUCTURE{ char Filename[MaxMP3Name]; uint8_t VolLeft; uint8_t VolRight; uint8_t Command; }; volatile RECEIVE_DATA_STRUCTURE RXdata; #define SLAVE_ADDRESS 77 volatile uint8_t newData; // flag to detect I2C activity // MAKE GLOBAL VERSIONS String RX_Filename; uint8_t RX_VolLeft = 30; uint8_t RX_VolRight = 30; uint8_t RX_Command = 0; ... etc //#################################// //## MASTER SENDING US DATA ##// //#################################// void onReceiveEvent(int numbytes){ if(numbytes == 16){ I2C_readAnything(RXdata); newData = 2; } } ... etc void loop(){ if (newData==2){// I2C received Data RX_Filename = RXdata.Filename; RX_VolLeft = RXdata.VolLeft; RX_VolRight = RXdata.VolRight; RX_Command = RXdata.Command; newData = 0; // Clear data sent marker } } ... etc </code></pre> <p>Hopefully you'll be able to see pretty quickly what i'm trying to do and the method I should be using to do it..</p> <p>Thanks for any insights</p> <p>Cheers</p> <p>Andy</p> <hr> <p>Sorry, still getting used to this comment vs editing questions business, didn't realise it would add my comment when I hit enter so it cut me off... here's full comment: </p> <hr> <p>Hiya Nick, thanks for your suggestion, How you've recommended it is actually how I tried it originally (I don't like using Strings either) - which just ends up giving me the error:</p> <p><code>"invalid conversion from 'volatile char*' to 'const char*' [-fpermissive]"</code></p> <p>(on the Slave) - obviously the RXdata is updated during the interrupt so can't leave it out (despite the fact it compiles - but doesnt work).. </p> <p>I got it working soon after I posted by breaking down the filename in the struct to separate chars, then assembling back into char array in a function I made. </p> <p>That seemed to work fine, but only if I added null char at as the last char (0x00) - I can get the char <code>Filename[MaxMP3Name];</code> working, but only if I lose the volatile declaration, and it skips the last char. </p> <p>Thanks for any further help Nick, I really appreciate all you do for the community and I know you're the best guy to help me (not to take anything away from anyone else that wants to jump in ;)</p> <h2>Current solution i'm using that avoids the volatile erros</h2> <p>Obviously could be a for loop etc but I wrote it out this way just to debug and see where the issue was. Not perfect, but breaking it down this way seems to be overcoming the issue of trying to do anything with the volatile variable. (and i've got so much to figure out for so many other parts of the project that I was thinking i'd come back to it later once i'm done with other bits).. Cheers</p> <pre><code>//#################################// //## SEND MP3 COMMAND ##// //#################################// void sendMP3Command(String MP3File, uint8_t Command) { char FileName[8]; MP3File.toCharArray(FileName, MaxMP3Name+1); txMP3.File1 = FileName[0]; txMP3.File2 = FileName[1]; txMP3.File3 = FileName[2]; txMP3.File4 = FileName[3]; txMP3.File5 = FileName[4]; txMP3.File6 = FileName[5]; txMP3.File7 = FileName[6]; txMP3.File8 = FileName[7]; txMP3.VolLeft = VolLeft; txMP3.VolRight = VolRight; txMP3.Command = Command; StartMicros = micros(); Wire.beginTransmission(MP3_SLAVE_ADDRESS); I2C_writeAnything(txMP3); Wire.endTransmission(true); EndMicros = micros(); //Serial.print("MP3 Packet Size: "); Serial.println(sizeof(txMP3)); //Serial.print("Sending Command To MP3: "); Serial.print(MP3File);Serial.print(" Command; "); Serial.print(txMP3.Command);Serial.print(" Time; "); Serial.print(EndMicros-StartMicros);Serial.println("uS "); } </code></pre> <p>... Oh, and on the slave end, I changed the numbytes to be sizeof, but as you say Nick, not even any need for that, i'm not using it on any of my other I2C slaves all running in the project (5 X MCU core system). the filename is then pulled from the I2C array in a siimilar (debugging) way as the master packs them in</p> <pre><code>//##############################// // RECONSTRUCT FILENAME //##############################// String getFilename(){ char FileName[] = { RXdata.File1, RXdata.File2, RXdata.File3, RXdata.File4, RXdata.File5, RXdata.File6, RXdata.File7, RXdata.File8, 0x00 }; return FileName; } //#################################// //## MASTER REQUESTING DATA ##// //#################################// void onRequestEvent(void){ I2C_singleWriteAnything(TXdata); newData = 1; } //#################################// //## MASTER SENDING US DATA ##// //#################################// void onReceiveEvent(int numbytes){ if(numbytes == sizeof RXdata){ I2C_readAnything(RXdata); newData = 2; } } </code></pre>
<p>This part looks weird:</p> <pre><code>void sendMP3Command(String MP3File, uint8_t Command) { char *TextArray[MaxMP3Name]; MP3File.toCharArray(TextArray, MaxMP3Name); txMP3.Filename = TextArray; </code></pre> <p>You have made an array of 13 pointers to strings. This is not what you want. You want the file name to end up into <code>txMP3.Filename</code>.</p> <p>This would be closer:</p> <pre><code>void sendMP3Command(String MP3File, uint8_t Command) { MP3File.toCharArray(txMP3.Filename, MaxMP3Name); </code></pre> <p>Personally I wouldn't be using the <code>String</code> class at all, but that should be better.</p> <hr> <p>Now:</p> <pre><code>void onReceiveEvent(int numbytes){ if(numbytes == 16){ I2C_readAnything(RXdata); newData = 2; } } </code></pre> <p>Are you <strong>sure</strong> it's 16 bytes? What if you change the struct? Let the compiler do the thinking for you:</p> <pre><code>void onReceiveEvent(int numbytes){ if(numbytes == sizeof (RXdata)){ I2C_readAnything(RXdata); newData = 2; } } </code></pre> <hr> <blockquote> <p>How you've recommended it is actually how I tried it originally (I don't like using Strings either) - which just ends up giving me the error "invalid conversion from 'volatile char*' to 'const char*' [-fpermissive]" (on the Slave) </p> </blockquote> <p>This minimal example compiles OK:</p> <pre><code>#include &lt;Wire.h&gt; #include &lt;I2C_Anything.h&gt; const uint8_t MaxMP3Name = 13; struct RECEIVE_DATA_STRUCTURE{ char Filename[MaxMP3Name]; uint8_t VolLeft; uint8_t VolRight; uint8_t Command; }; volatile RECEIVE_DATA_STRUCTURE RXdata; volatile uint8_t newData; // flag to detect I2C activity void onReceiveEvent(int numbytes){ if(numbytes == sizeof RXdata){ I2C_readAnything(RXdata); newData = 2; } } void setup() { } void loop() { } </code></pre>
17062
|arduino-uno|shields|sd-card|tmrpcm|
SD card fails to initialize
2015-10-21T14:56:51.837
<p>I know this question has be asked before on this site. However it was never really answered. I have an Arduino Uno. I am trying to get it to read a 2 GB SDHC Micro SD card. The problem is, the SD card never intializes. I am not sure if there is something wrong with the wiring (which I think is NOT the issue) or the SD card/shield. I have formatted the SD card, but perhaps I did use the wrong settings to do so. Additionally, this SD card is quite old, probably several years. It can still be managed on my PC however.</p> <p>I bought the following <a href="https://rads.stackoverflow.com/amzn/click/B015VH43WM" rel="nofollow noreferrer">Micro SD shield off Amazon.</a> It has the pins VCC, GND, MISO, CS, MOSI, and SCK, for which I figured the following:</p> <pre><code>MISO = D0 CS = D1 MOSI = CLK SCK = D3 </code></pre> <p>I have the circuit wired in the following way:</p> <pre><code>SCK to Pin 10 on Arduino CS to Pin 11 on Arduino MISO to Pin 12 on Arduino MOSI to Pin 13 on Arduino VCC to 3.3V source on Arduino GND to Arduino Ground </code></pre> <p>The image below is a compilation of the closeup of the shield and my wiring. Not that I am also using Pin 9 in the picture. However this is used for a different portion of the circuit.</p> <p><a href="https://i.stack.imgur.com/IfhE9.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IfhE9.jpg" alt="enter image description here"></a></p> <p>The code that I am trying to run comes from the SdFat library. Though the Amazon page says the device can be used without this library, I prefer to have it. I am running the <code>SdInfo.ino</code> example located in SdFat/SdFat/examples/SdInfo/. I have changed the coding so that:</p> <pre><code>const uint8_t SD_CHIP_SELECT = 10; </code></pre> <p>I have also tried running the <code>Basic.ino</code> example in the TMRpcm library, located at: TMRpcm/examples/basic, but this doesn't work either. Below is the code:</p> <pre><code>#include &lt;SD.h&gt; // need to include the SD library //#define SD_ChipSelectPin 53 //example uses hardware SS pin 53 on Mega2560 #define SD_ChipSelectPin 10 //using digital pin 4 on arduino nano 328, can use other pins #include &lt;TMRpcm.h&gt; // also need to include this library... #include &lt;SPI.h&gt; TMRpcm tmrpcm; // create an object for use in this sketch void setup(){ tmrpcm.speakerPin = 9; //5,6,11 or 46 on Mega, 9 on Uno, Nano, etc Serial.begin(9600); if (!SD.begin(SD_ChipSelectPin)) { // see if the card is present and can be initialized: Serial.println("SD fail"); return; // don't do anything more if not } tmrpcm.play("music"); //the sound file "music" will play each time the arduino powers up, or is reset } void loop(){ if(Serial.available()){ if(Serial.read() == 'p'){ //send the letter p over the serial monitor to start playback tmrpcm.play("music"); } } } </code></pre> <p>In short. My SD card does not initialize, and I cannot seem to figure out why.</p>
<p>The solution to this problem, is that you have to let digital Pin 10 as output (for the SD library to work) and put out a logic HIGH by adding “digitalWrite(10,HIGH);”. For Arduino Mega you have to do exactly the same ignore pin 53 completely though the comment asks you to change it to 53.</p> <p>pinMode(10, OUTPUT); // change this to 53 if you are using arduino mega<br> digitalWrite(10, HIGH); // Add this line</p>
17072
|arduino-uno|shields|analogread|
Using digital weighing scales with INA125p
2015-10-21T20:08:15.867
<p>Complete electronics beginner here. I'm attempting to build a weighing scale with an Arduino. </p> <p>I'm attempting to follow <a href="http://www.open-electronics.org/wi-fi-body-scale-with-arduino/" rel="nofollow noreferrer">this tutorial</a>, with the shield that they use.</p> <p><a href="https://i.stack.imgur.com/TMFhq.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TMFhq.jpg" alt="enter image description here"></a></p> <p>I've arranged my load cells on the scale into a Wheatstone Bridge, and I can get some readings just by taking a voltage reading from the two cells marked V+ and V-. The board has terminals that are linked to a INA125p, and the pins should give an amplified reading.</p> <pre><code>Pin A1:0.96 Pin A2:1.42 Pin A3:5.00 Pin A4:5.00 Pin A5:5.00 </code></pre> <p>Regardless of whether I have the scale wired in or not, I get these readings from the individual pins. The scales seem to be able to take power from the Arduino shield.</p> <p>The scales that I have are different from the ones in the example. From what I can figure out, the yellow cables that they reference turn their particular scale on when weight is put on it.</p> <p>I've put the wires where I take the reading into the 2 and 4 terminals on the circuit board that they have (where the tutorial references a differential signal), but again, it makes no change.</p> <blockquote> <p>unsolder or cut the white wire that is referred to as G3 (Wheatstone bridge mass) on the original printed circuit, extend take it to terminal 1 on the new printed circuit;</p> <p>unsolder or cut the white wire that is referred to as G2 (Wheatstone bridge positive) on the original printed circuit, extend take it to terminal 3 on the new printed circuit;</p> <p>unsolder or cut the white wire that is referred to as G1 and G4 on the original printed circuit, extend take it to terminal 4 and 2 on the new printed circuit (differential signal on the Wheatstone bridge)</p> </blockquote> <p>I've attempted lots of different combinations of cables and terminals on the new circuit, but it appears to make no difference to the readings.</p> <p>My question is: Based on the tutorial and the drawing above, am I taking the readings from the correct place? Are there any things I'm obviously doing wrong with the circuit itself? If the circuit is correct, how would I go about trying to get correct readings from the scale when I add weight to it?</p> <p>I apologise for the vague nature of this question, but I am a complete beginner trying to figure this out, and I am struggling to follow the tutorial. I'll try and provide any additional information that you need.</p> <p>EDIT - I have a Salter SAL-3003 SSSVDR08 scale.</p> <p>Each load cell has 3 cables, Red, Black and White. The red ones are the ones marked with the V+, V- etc. On the original board, they were wired in threes.</p>
<p>Fixed (to some extent)! Faulty connection between the INA125p and the plint it was sitting in. I refitted it and i'm now getting varied readings with the scales, but that's to be expected with the noise the INA125p generates.</p>
17092
|arduino-uno|shift-register|
Multiple shift registers, 16 bit numbers
2015-10-22T12:26:43.883
<p>Currently working on understanding shift registers and traing to display binary number from 65535 to 0 on a 16 LED's. Below you can see schematics I am using.</p> <p><a href="https://i.stack.imgur.com/5X4Y1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5X4Y1.png" alt="Used topology"></a> The code I am using is </p> <pre><code>int latchPin = 8; int clockPin = 12; int dataPin = 11; int numberToDisplay=65535; void setup() { pinMode(latchPin, OUTPUT); pinMode(clockPin, OUTPUT); pinMode(dataPin, OUTPUT); } void loop() { digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, numberToDisplay); digitalWrite(latchPin, HIGH); delay(500); } void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val) { uint8_t i; for (i = 0; i &lt; 16; i++) { if (bitOrder == LSBFIRST) digitalWrite(dataPin, !!(val &amp; (1 &lt;&lt; i))); else digitalWrite(dataPin, !!(val &amp; (1 &lt;&lt; (15 - i)))); digitalWrite(clockPin, HIGH); digitalWrite(clockPin, LOW); } } </code></pre> <p>Problem is when I change numberToDisplay from 0 to 225, everything works and LEDs are lighted correspondingly (if numberToDisplay=225 all red lights are on). But if numbers are bigger than 225 everything just stops working and nothing lights up.</p> <p>Thank you in advance</p>
<p>Your problem is entirely that you declare val to be uint8_t, instead of uint16_t. You are truncating your data to 8 bits before displaying it. One other note, the 74HC595 has a maximum total drive current of 50mA. Your circuit will draw around 90mA for each of the 74HC595's if all of the LEDs are on. You may want to change the resistors to something bigger (510 Ohm, for example) to avoid this problem. Of course that will make the LEDs dimmer, so it's a tradeoff. Here's <a href="https://123d.circuits.io/circuits/1142474" rel="nofollow noreferrer">your project in 123D Circuits</a>. You can simulate it in the browser and look at the code running in the Arduino there.</p> <p><a href="https://i.stack.imgur.com/QxbeP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QxbeP.png" alt="enter image description here"></a></p>
17104
|arduino-uno|
Trying to understand Arduino products
2015-10-22T19:23:31.037
<p><strong>Background:</strong></p> <p>I am new to Arduino world, and I like to buy a board. I am a bit confused how Arduino products are being sold. Coming from Raspberry world, it seems that I don't know what actually Arduino is. </p> <p><strong>Question</strong>:</p> <p>I am trying to understand what is it that this product offers:</p> <p><a href="https://i.stack.imgur.com/KfpYB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KfpYB.png" alt="Arduino UNO R3"></a></p> <p>.</p> <ol> <li>Why it says "<strong>For</strong> Arduino UNO R3"? 2. Isn't it actually an "Arduino UNO R3"? So why it says "For"?</li> <li>What are MEGA328P and CH340? Does "Arduino UNO R3" comes with other chipsets?</li> </ol>
<p>It sounds to me like an Arduino Uno <strong>clone</strong>.</p> <blockquote> <p>Why it says "For Arduino UNO R3"? </p> </blockquote> <p>I would read that as "For Arduino UNO R3 <strong>projects</strong>" (ie. Uno-compatible).</p> <blockquote> <p>Isn't it actually an "Arduino UNO R3</p> </blockquote> <p>No, it's a clone. Or not really a clone (see below) because they used different hardware. It is compatible with the Uno in most respects.</p> <blockquote> <p>What are MEGA328P?</p> </blockquote> <p>That is the <strong>main</strong> chip on the board (actually an Atmega328P).</p> <blockquote> <p>and CH340?</p> </blockquote> <p>They have saved money by using a CH340 USB-to-serial chip instead of the Atmega16U2 used on genuine Uno boards. You may need to install a different driver to make that work. I disagree with the other answer(s) that this is a separate board or chip. It is clear from the photo of the chip near the USB socket that it is a CH340 chip there. See, for example <a href="https://hackaday.com/tag/ch340/" rel="nofollow">https://hackaday.com/tag/ch340/</a> from which I quote:</p> <blockquote> <p>The cheapest USB to serial chip on the market appears to be the CH340G, available for 20-40 cents apiece from the usual retailers. There is, however, almost no English documentation, and the datasheet for the CH340 family doesn’t include this chip</p> </blockquote> <p>They used it because it is cheap.</p> <blockquote> <p>Does "Arduino UNO R3" comes with other chipsets?</p> </blockquote> <p>Yes the <strong>genuine</strong> one comes with an Atmega328P (main processor) and Atmega16U2 (USB interface).</p> <hr> <p>Having said all that, the Uno is a good all-rounder starting board to get going with Arduinos.</p> <p>Note that they are using the SMD (surface mounted) main processor chip. If you fry it you need to replace the whole board, not just the chip. However the entire board is quite cheap. :)</p>
17154
|usb|input|pins|
How to add more inputs on Arduino?
2015-10-24T18:05:41.010
<p>I'm building an instrument that has 72 buttons that can be pressed. Now I'm planning on using Arduino to send data to computer via USB cable about which buttons are pressed. So I figured I'd need 72 different input pins, one for each button(the button is connected to the Arduino via a wire). But, the Arduino doesn't have 72 input pins, so this seems kind of impossible. So what I'm looking for is a way to somehow extend the number of pins on the Arduino or another way to solve my problem. Maybe it would be better to use another micro-controller? Maybe using analog inputs for this is better?</p> <p>If it makes any difference, the max number of buttons that can be pressed at once is 10.</p>
<p>There are quite a few GPIO expanders available that you could use to increase IO lines in your circuit, mostly running off I2C. Just search "I2C GPIO" on your favorite electronics site/google/ebay</p> <p>Examples: <a href="https://www.sparkfun.com/products/8130" rel="nofollow">https://www.sparkfun.com/products/8130</a> [No affiliation]</p> <p>If every sensed key has to be on a GPIO, then this is the way to go.</p> <p>Having said that, with IO expanders, you will find that sensing large number of keys still takes lots of code on your uC. With some extra software effort, you could eliminate expanders, and rather scan a key matrix as suggested by Majenko</p>
17158
|arduino-uno|motor|transistor|h-bridge|
DC motor kickback diode?
2015-10-24T19:04:53.647
<p>I have the following circuit: <a href="https://i.stack.imgur.com/lZJDW.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lZJDW.jpg" alt="Arduino circuit"></a></p> <p>And I know it works and that the diode protects the negative voltage from flowing back into the transistor. This is essentially the circuit: <a href="https://i.stack.imgur.com/qGZ9h.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qGZ9h.jpg" alt="Circuit"></a></p> <p>Could someone illustrate what happens when the motor stops? The current normally flows from 5V to GND (and the electrons from GND to 5V, but this doesn't matter (I think?)), and then it reverses when you switch it off, so current comes out of the top of M1, and then what? I don't get it here.</p>
<p>While the motor is being powered the current flows from Vcc to GND as in this circuit:</p> <p><a href="https://i.stack.imgur.com/QULAI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QULAI.png" alt="enter image description here"></a></p> <p>When the power is disconnected (such as the transistor in the ground connection in your circuit is switched off) amongst other things (including the collapsing of magnetic fields) the spinning of the motor turns it into a generator. The power generated is the opposite of what was being provided to make it move. As the magnetic field of the coils collapses additional high voltages are also generated.</p> <p>When disconnected the motor can be represented as a battery connected backwards. In that configuration the current flows from the + of this hypothetical battery through the diode into the - thus stopping any current from going elsewhere, as in this circuit:</p> <p><a href="https://i.stack.imgur.com/1Rjim.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1Rjim.png" alt="enter image description here"></a></p>
17160
|ir|
How to use Infra Red (IR) to reset arduino board
2015-10-24T21:57:59.150
<p>I am a big noob I know that</p> <p>but can this code be used to reset arduino board (instead of pressing the usual reset button on the board) </p> <p>I want to reset the board as If am pressing the reset button using IR </p> <pre><code>int receiverpin = 2; // pin 1 of IR receiver to Arduino digital pin 2 #include &lt;IRremote.h&gt; IRrecv irrecv(receiverpin); // create instance of irrecv decode_results results; void setup() { irrecv.enableIRIn(); // start the receiver } void(* resetFunc) (void) = 0; //declare reset function @ address 0 void loop() { if (irrecv.decode(&amp;results)) // have we received an IR signal? { if(results.value == 0x2FD847B) //if the button press equals the hex { resetFunc(); } { irrecv.resume(); // receive the next value } } } </code></pre>
<p>Kind of, yes. That doesn't actually reset the Arduino, it just sends the program to address 0.</p> <p>There are two other ways of performing the reset that do a proper full reset:</p> <ol> <li>Enable the watchdog timer and let it time out to reset the CPU.</li> <li>Connect an IO pin to the RESET pin - keep it in INPUT most of the time but set it to OUTPUT and LOW when you want to reset.</li> </ol> <p>By just jumping to address 0 you aren't resetting the internal peripherals and registers to their reset state, so things like timers and such will still be running when they shouldn't be, etc. It's better by far to do a real reset instead of just jumping to 0 like that.</p>
17164
|safety|timing|
Verifying the timing between relay activations
2015-10-25T00:27:35.020
<p>I would like to verify timings of a relay controlled by an arduino (uno R3). There is a lot going on in the sketch and it does not use the delay function but one which is based on <a href="https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay" rel="nofollow">counting milliseconds</a>. The arduino then transmits to another arduino using a radio module (nRF24L01). I'd like to confirm the intervals between the relay, so for instance if the relay is acivated 10 times and there are 5 seconds between each actvation.</p> <p>So what I was wondering was whether anyone had any reccomendations on methods to verify timings using an external source.</p> <p>Two ideas I came up with were: have another arduino with a very simple script that measures the timings or try and find/write a verilog script to upload to a mojo fpga and measures the timings.</p> <p>An ideal situation would be where I have a seperate device that hooks up to the relay and then measures and displays the timings between the relay switches and is extremely precise.</p> <p>I hope that makes sense, if not please let me know and I'll explain further. Thank you for reading and any help is greatly appriciated.</p>
<p>You could use <a href="http://sigrok.org" rel="nofollow">sigrok</a> with one of the many <a href="http://sigrok.org/wiki/Supported_hardware" rel="nofollow">supported devices</a>. For example, you can find on ebay an <a href="http://sigrok.org/wiki/MCU123_USBee_AX_Pro_clone" rel="nofollow">8 channell 24MHz probe</a> for less than $10.</p> <p>It's a nice tool to have laying around. For example you can use it as less-invasive-than-serial-print way to detect when internal states of a program change value: just toggle some unused GPIO.</p>
17176
|arduino-uno|uploading|sketch|
Sketch upload freezes during write
2015-10-25T18:00:20.437
<p>I'm trying to upload a huge sketch to my <strong>Uno R2</strong>. It's compiling just fine but it fails to upload at 94% of writing to flash...</p> <p>The program is so large because of a big array of data in a separate .h file:</p> <pre><code>#include &lt;avr/pgmspace.h&gt; const unsigned char PROGMEM data[] = { 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x7f, 0x80, 0x7f, 0x80, 0x7f, 0x80, (etc...) </code></pre> <p>A test sketch with just 12 bytes of data uploads fine, so the problem is either with the size or some weird bug triggered by some of the data.</p> <p>Unless i'm missing something, this should technically work.</p> <p>Command:</p> <pre><code> /home/hatagashira/.arduino-1.6.5/hardware/tools/avr/bin/avrdude -C/home/hatagashira/.arduino-1.6.5/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/ttyACM0 -b115200 -D -Uflash:w:/tmp/build8921209068074674980.tmp/program.cpp.hex:i </code></pre> <p>Output:</p> <pre><code>avrdude: Version 6.0.1, compiled on Apr 14 2015 at 19:04:16 Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/ Copyright (c) 2007-2009 Joerg Wunsch System wide configuration file is "/home/hatagashira/.arduino-1.6.5/hardware/tools/avr/etc/avrdude.conf" User configuration file is "/home/hatagashira/.avrduderc" User configuration file does not exist or is not a regular file, skipping Using Port : /dev/ttyACM0 Using Programmer : arduino Overriding Baud Rate : 115200 Setting bit clk period : 5.0 AVR Part : ATmega328P Chip Erase delay : 9000 us PAGEL : PD7 BS2 : PC2 RESET disposition : dedicated RETRY pulse : SCK serial program mode : yes parallel program mode : yes Timeout : 200 StabDelay : 100 CmdexeDelay : 25 SyncLoops : 32 ByteDelay : 0 PollIndex : 3 PollValue : 0x53 Memory Detail : Block Poll Page Polled Memory Type Mode Delay Size Indx Paged Size Size #Pages MinW MaxW ReadBack ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- --------- eeprom 65 20 4 0 no 1024 4 0 3600 3600 0xff 0xff flash 65 6 128 0 yes 32768 128 256 4500 4500 0xff 0xff lfuse 0 0 0 0 no 1 0 0 4500 4500 0x00 0x00 hfuse 0 0 0 0 no 1 0 0 4500 4500 0x00 0x00 efuse 0 0 0 0 no 1 0 0 4500 4500 0x00 0x00 lock 0 0 0 0 no 1 0 0 4500 4500 0x00 0x00 calibration 0 0 0 0 no 1 0 0 0 0 0x00 0x00 signature 0 0 0 0 no 3 0 0 0 0 0x00 0x00 Programmer Type : Arduino Description : Arduino Hardware Version: 3 Firmware Version: 3.3 Vtarget : 0.3 V Varef : 0.3 V Oscillator : 28.800 kHz SCK period : 3.3 us avrdude: AVR device initialized and ready to accept instructions Reading | ################################################## | 100% 0.00s avrdude: Device signature = 0x1e950f avrdude: safemode: lfuse reads as 0 avrdude: safemode: hfuse reads as 0 avrdude: safemode: efuse reads as 0 avrdude: reading input file "/tmp/build8921209068074674980.tmp/program.cpp.hex" avrdude: writing flash (30110 bytes): Writing | ############################################### | 94% 5.10savrdude: stk500_recv(): programmer is not responding </code></pre>
<p>My two arduino nanos did flash and run the program correctly. I suspect a problem with the uno's serial communication but unwilling to troubleshoot further (i only have one uno). I decided to switch to the nano for further prototyping.</p>
17179
|pwm|multiplexer|rgb-led|
Using 2 RGB lights over Bluetooth with a DigiSpark
2015-10-25T19:31:38.667
<p>I'm not that experienced with electronics but I am learning. And I've set a challenge for myself. I have a Digispark USB Development board (and many more but I want to use this one!), I have a Bluetooth module and I have two RGB LEDs which I want to control over the Bluetooth connection. Each LED has to be controlled separately and I want to be able to set each color separately and be able to mix about 256x256x256 colors. Which means, PWM connections. The Bluetooth connection would listen to instructions, receiving four bytes containing RGB values and a value between 0 and three to pick which light needs to be set. (0=None, 1=left, 2=right, 3=both)<br> Also important is that it needs to be small. It will end up in a container of of roughly 3x3x10 CM in size. (Slightly bigger than 1x1x3 inch.) </p> <p>The challenge is that Digispark only has 6 pins available so that's not enough to handle this all. I could use three pins and use a 74HC165N Shift Register but that would just turn each color on or off, thus limiting me to 8 colors. That's not good enough! Besides, I also need to connect the four pins of the Bluetooth module. </p> <p>So my question is simple: What would I need more to build this project? To send the proper six analog signals while having enough pins to handle the Bluetooth datastream? </p>
<blockquote> <p>Which means, analog connections.</p> </blockquote> <p>Nope. It means PWM.</p> <p>How would you control the brightness of a single LED?</p> <p>By generating a PWM signal with:</p> <ul> <li><p>sufficiently high frequency to not be able to notice the flickering;</p></li> <li><p>duty cycle proportional to the brightness you want/need, where 100% is full brightness, and 0% is OFF</p></li> </ul> <p>You only have to do that for each colour of the RGB LED you want to drive. Ideally you would use a HW block capable of generating the PWM signal, but it can be also bit-banged, should you run out of PWM blocks.</p> <p>Just keep in mind that different colours have different currents (for the same level of brightness), so you have to pay attention at calculating the correct value of the resistor applied to each colour.</p> <p>If you prefer to ensure that each channel is driven by a HW PWM generator, you can also use an external driver. Ex: <a href="http://www.intersil.com/en/products/audiovideo/display-ics/led-backlight-drivers/ISL97671A.html" rel="nofollow">I2C 6-channels PWM generator</a>.</p>
17183
|serial|arduino-ide|edison|
Open the Uart0 Serial Port on Intel Edison
2015-10-25T20:39:42.223
<p>I'll preface this buy saying I am very new to working with Arduino boards or hardware in general. I am attempting to follow a tutorial on instructables</p> <p><a href="http://www.instructables.com/id/PCBot/step4/Printer-test/" rel="nofollow">http://www.instructables.com/id/PCBot/step4/Printer-test/</a></p> <p>I have my board and printer wired up properly and I have git cloned the python thermal printer. My issue begins at this paragraph:</p> <blockquote> <p>Open the UART0 serial port by default the GPIO's of the edison are disables.</p> <p>You can enable them by programming the edison via the Arduino IDE or by using the MRAA library available for several programming languages.</p> <p>To open enable the UART0 port, TX RX on the edison breakout board, open a Python shell in the thermal and write:</p> <p>import mraa</p> <p>x=mraa.Uart(0) </p> </blockquote> <p>I opened a python shell and entered the <code>import mraa</code> lines and tried to run the <code>printertest.py</code></p> <p>I receive an error that says no module named serial. I am not sure where the issue is. I thought the Edison already had python serial installed. I did try to install it with <code>opkg install python-serial</code> but it didn't work. If my issue is with enabling the Uart0 port I am not sure how to go about doing it. I have the Arduino IDE installed but I have no idea how to go about enabling it via the Arduino IDE. The instructions are a bit vague in that paragraph. </p> <p>*Update I have successfully installed pip and got pyserial installed. Now when I try to run the printertest.py I get an error <code>OSError: [Errno 2] No such file or directory: '/dev/ttyAMA0'</code> which I think is potentially caused by me not succesfully opening Uart0 port but I am not sure how to. I tried adding the import in a shell as well as adding it directly to the code via nano</p>
<p>I have solved the issues and successfully connected this printer with the Compute Module. I solved the issue by changing the target of <code>/dev/ttyAMA0</code> to <code>/dev/ttyMFD1</code> as shown by <a href="http://iotdk.intel.com/docs/master/mraa/edison.html" rel="nofollow">http://iotdk.intel.com/docs/master/mraa/edison.html</a> . This was the final step after I had installed pyserial.</p>
17188
|arduino-uno|esp8266|
Problem with connecting ESP8266 to arduino
2015-10-26T07:30:52.110
<p>I have:</p> <ul> <li>Arduino Uno</li> <li><a href="https://rads.stackoverflow.com/amzn/click/B00PI6TO8U" rel="nofollow noreferrer">ESP8266</a></li> </ul> <p>Problem: I see SoftAP and can connect to it. But I can't send AT-commands to ESP8266 from Arduino. I use Arduino app v.1.6.5 for send command to ESP8266 via Arduino. But I don't get answer. And ESP8266 doesn't blinking.</p> <p>I use this scheme:</p> <p><a href="https://i.stack.imgur.com/Co7kW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Co7kW.png" alt="Scheme for connecting Arduino and ESP8266"></a></p> <p>Please, help me. I'm trying to fix this is very time consuming.</p>
<p>You must need to add another power supply, which will give to the wifi module not just the correct voltage (3v) but the mA that it need. / other thing you may need to do is connect the ground of Arduino to Ground of the power supply. For me works good. </p> <p>the connections would be like this</p> <ol> <li>esp TX > arduino dpin 10 </li> <li>esp RX > arduino dpin 11</li> <li>esp CH > to VCC 3V</li> <li>esp RST > to pushbutton connected to gnd</li> <li>esp GpIO 0 > none</li> <li>esp GpIO 2 > none</li> <li>esp VCC > power supply 3v</li> <li>esp GND > power supply gnd</li> </ol>
17189
|arduino-uno|
Extracting high and low bytes from long
2015-10-26T10:24:06.840
<p>I am learning Arduino from "Arduino cookbook by Michael Margolis", i was reading about bitwise operations and extracting low and high bytes from int. He said that there is no function in Arduino to extract high and low bytes from long at the time of his writing. He stated an alternative to the problem by adding two line of code.</p> <pre><code>#define highWord(w) ((w) &gt;&gt; 16) #define lowWord(w) ((w) &amp; 0xffff) </code></pre> <p>The first line i clearly understood like this, please make corrections if i am wrong.</p> <pre><code>32bit binary of 16909060 is 0000 0001 0000 0010 0000 0011 0000 0100 </code></pre> <p>by right shifting last 16 bits we will arrive at </p> <pre><code>32bit binary of 16909060 after right shifting 16bits is 0000 0000 0000 0000 0000 0001 0000 0010 </code></pre> <p>I am not able to interpret the second line. </p> <pre><code>#define lowWord(w) ((w) &amp; 0xffff) </code></pre> <p>I would be very grateful if some body explain how the above line of code works? Thanks. </p>
<p>An alternative way of seeing the two operations is through the operators "integer division" and "reminder of the integer division".</p> <p>In a more generic fashion:</p> <p><code>#include &lt;limits.h&gt;</code></p> <p><code>#define highBits(value, number_of_high_bits) \ (value / (1 &lt;&lt; (sizeof(value) * CHAR_BIT - number_of_high_bits)))</code></p> <p><code>#define lowBits(value, number_of_high_bits) \ (value % (1 &lt;&lt; (sizeof(value) * CHAR_BIT - number_of_high_bits)))</code></p> <p>This will work regardless the number of bits used for <code>value</code> and with an arbitrary number of <code>high_bits</code> to either keep or shave.</p>
17195
|arduino-uno|sensors|
Capacitive sensor MPR121 on Arduino Uno—how many will work?
2015-10-26T15:19:47.413
<p>I need to attach several capacitive sensors MPR121 with each of them using all of its 12 electrodes to an Arduino Uno.</p> <p>Could you please tell me, how many will work with the voltage and current Arduino Uno supplies?</p>
<p>The answer is 4 regardless of the current consumption.</p> <p>You can have 4 MPR121 devices on an I2C bus (by connecting the ADDR pin to the right place to select 1 of 4 addresses), and the Uno has one I2C bus - so that means 4 devices.</p> <p>You <em>could</em> use software I2C to add more devices on other pins, but that's slow and clunky.</p> <p>But that aside, if you used something to increase the number of I2C buses available, according to the datasheet the peak current consumption is 1mA during sampling, and assuming 300mA maximum for the Arduino's 3.3V regulator, that would mean a maximum of 300 MPR121 connected to the Arduino. Note that, if you could actually <em>get</em> to the Arduino amongst that tangle of wires, you'd find it getting rather hot...</p>
17201
|arduino-due|wireless|
433Mhz transmitter interference when using long cable, only on Arduino Due
2015-10-26T17:20:10.277
<p>When the 433 transmitter is wired close to the Arduino Due (within 12" away), it works as expected. But when I put it on the end of a 15' cable, it has the following 2 symptoms:</p> <p>-All the other nearby 433Mhz transmitters and receivers stop working. (I've never seen this happen from any other cause).</p> <p>-My Extech 480836 EMF meter shows a big jump in electromagnetic radiation along the entire length of the 15' cable (it jumps from <em>0.1 uW/m2</em> to <em>3 mW/m2</em> a few inches away). The reading only goes down to normal if I unplug the transmitter's data wire from the Arduino.</p> <p>The transmitter in question is still able to send signals correctly when wired with a 15' cable to the Due (properly activating remote switches), even though it disables every other 433 transmitter in the area.</p> <p>I've tested this with 2 different kinds of 433 transmitters, getting the same result. Both of the transmitters work fine whenever wired closely to the Arduino Due, and both work as expected when connected to an Arduino Uno. The problems still occur even if I'm not sending any wireless transmissions from the code. Disconnecting the transmitter's data wire from the Arduino Due causes the problem to stop immediately.</p> <p>I'm using the <a href="https://github.com/sui77/rc-switch" rel="nofollow">RCSwitch library</a>. The simple code below works fine on an Arduino Uno, whether the transmitter is wired far or close to the Uno. The same code works fine with the Due when the transmitter is close to the Due. But when the transmitter is wired 15' away from the Due, then the problems occur. On the Due I've tested using 5v and 3v for powering the transmitter. Changing the voltages doesn't seem to affect the problem.</p> <pre><code>#include &lt;RCSwitch.h&gt; RCSwitch mySwitch = RCSwitch(); void setup() { Serial.begin(9600); // Transmitter is connected to Arduino Pin #8 mySwitch.enableTransmit(8); } void loop() {} </code></pre> <p>Why am I having this strange behavior? Do you have any suggestions on how to fix it?</p>
<p>I think I found the problem. It seems that there's an anomaly with the Due where when a pinmode is set as OUTPUT, it sets the pin as HIGH by default, whereas with the other Arduinos it's set as LOW. This forum page is discussing the problem: <a href="http://forum.arduino.cc/index.php?topic=154869.0" rel="nofollow">http://forum.arduino.cc/index.php?topic=154869.0</a></p> <p>Likewise this page suggests the problem is a bug with the wiring_digital.c file: <a href="http://forum.arduino.cc/index.php?topic=185230.0" rel="nofollow">http://forum.arduino.cc/index.php?topic=185230.0</a></p> <p>In RCSwitch.cpp, this is the enableTransmit code:</p> <pre><code>void RCSwitch::enableTransmit(int nTransmitterPin) { this-&gt;nTransmitterPin = nTransmitterPin; pinMode(this-&gt;nTransmitterPin, OUTPUT); } </code></pre> <p>It seems the code sets the pin as OUTPUT, which would cause an anomaly on the Due alone.</p> <p>I solved the problem by calling the enableTransmit function just before sending a signal, and then calling disableTransmit() immediately afterwards. Can anyone think of a cleaner/better solution?</p> <p>Out of curiosity, can anyone suggest what a standard transmitter might be sending when the data line is constantly held at HIGH?</p>
17203
|uart|
How to read the serial data from a ATMEGA8 on a PC using Arduino?
2015-10-26T18:16:34.100
<p>I want to check if a device is working or not. It is a custom made PCB with a Atmega8. It was given to me along with the AVR code. How do I read the data that it sends on my laptop using a arduino, preferably a Arduino Uno?</p> <p>I tried connecting the output UART pin to the Rx of the arduino, and then provided the common ground. Then I opened serial monitor on my laptop but I a m not getting anything. Is it because the PCB is damaged or am I doing it wrong?</p> <p>I have the AVR code which was burned on the IC, so I can provide you with more information if you need.</p>
<p>If you connect the TX pin on your device to the 'TX' pin on the Arduino, then load a sketch such as 'blink' that won't initialize the Arduino's own UART, you can use the Arduino's onboard USB-UART adapter to talk to your device.</p>
17206
|c++|arduino-due|datalogging|processing-lang|
pushing accelerometer data in packets from an arduino due to the pc and unto processing
2015-10-26T21:52:20.857
<p>I'm quite a newbie to this and I've been struggling for sometime now with my school project, trying to find a way to send accelerometer data from my MMA7361 in data packets, I understand that I have to send the data in packets, but I'm having problems going about it. One of the requirements of the project is that I have to send the data in array-packets of all the individual axes (e.g. a buffer array to hold the x-axis value, another for the y-axis value and also for the z-axis value). I have read quite a lot of documentation on the internet about this but putting it together is a challenge. Below is the infamous MMA7361 code sketch, do please help out if you can thankyou. </p> <pre><code> #include &lt;AcceleroMMA7361.h&gt; AcceleroMMA7361 accelero; int x; int y; int z; void setup(){ Serial.begin(9600); accelero.begin(13, 12, 11, 10, A0, A1, A2); accelero.setARefVoltage(3.3); //sets the AREF voltage to 3.3V accelero.setSensitivity(LOW); //sets the sensitivity to +/-6G accelero.calibrate(); } void loop(){ x = accelero.getXRaw(); y = accelero.getYRaw(); z = accelero.getZRaw(); Serial.print("\nx: "); Serial.print(x); Serial.print("\ty: "); Serial.print(y); Serial.print("\tz: "); Serial.print(z); delay(500); //(make it readable) } </code></pre>
<p>It's pretty simple to store the x, y and z co-ordinates in three separate arrays. Instead of storing them in single <code>int</code> variables you can just store them in <code>int</code> arrays. You can make three arrays that are of size 1000 a store the raw values there. In order to iterate through the arrays within <code>loop()</code> you can set up <code>i</code> at global scope and include an if statement that will know when the arrays are filled, for example <code>if (i == 1000)</code> and within this if statement you can set up a <code>for</code> loop that will iterate through the arrays and print their values and after reset <code>i</code> to <code>0</code> and then reset the buffer arrays i.e. fill them with zeroes. This last step is not needed since they will be overwritten anyway but it is good to have so you don't accidentally use old values. </p> <p>Also the <code>for</code> loop that will print the values will take 8 minutes with that <code>delay(500);</code> You can make this delay smaller or print the value before each <code>if</code> statement as the data comes in.</p> <pre><code>#include &lt;AcceleroMMA7361.h&gt; AcceleroMMA7361 accelero; int xAxisBuffer [1000] = {0}; int yAxisBuffer [1000] = {0}; int zAxisBuffer [1000] = {0}; int i = 0; void setup(){ Serial.begin(9600); accelero.begin(13, 12, 11, 10, A0, A1, A2); accelero.setARefVoltage(3.3); //sets the AREF voltage to 3.3V accelero.setSensitivity(LOW); //sets the sensitivity to +/-6G accelero.calibrate(); } void loop(){ // This stores the x, y and z values in their // respective arrays xAxisBuffer[i] = accelero.getXRaw(); yAxisBuffer[i] = accelero.getYRaw(); zAxisBuffer[i] = accelero.getZRaw(); ++i; // moves to the next position if (i == 1000){ // the arrays are full // prints the (x, y, z) values // because the delay is .5 seconds it will // take about 8 minutes to print all 1000 for (int j = 0; j &lt; 1000; j++){ Serial.print("\nx: "); Serial.print(xAxisBuffer[j]); Serial.print("\ty: "); Serial.print(yAxisBuffer[j]); Serial.print("\tz: "); Serial.print(zAxisBuffer[j]); delay(500); //(make it readable) } // restart at beginning of the arrays i = 0; // reset the arrays memset(xAxisBuffer,0,sizeof(xAxisBuffer)); memset(yAxisBuffer,0,sizeof(yAxisBuffer)); memset(zAxisBuffer,0,sizeof(zAxisBuffer)); } } </code></pre>
17211
|uploading|core-libraries|
Requesting references for learning about the upload process
2015-10-27T01:25:42.373
<p>I would like to know of references that discuss the process of uploading code onto an Arduino board. I have read this <a href="https://www.arduino.cc/en/Hacking/BuildProcess" rel="nofollow">reference</a> on hacking the Arduino and an outline of the build process. I also found this <a href="https://www.arduino.cc/en/Hacking/LibraryTutorial" rel="nofollow">segment</a> on creating Arduino libraries informative. </p> <p>Overall I am interested in tracing through an upload process to learn more detail about how the programming works. I would like to understand which C-libraries are used. I would like to understand how the code is uploaded onto the Arduino. One example that I would like to see is an direct upload of C or C++ code without using the IDE gui. I want to see kind of the "bare-minimum" necessary for programming the Arduino (in C/C++). I would ideally like to read about something like this which makes use of the Arduino libraries.</p> <p>Looking forward to hearing back responses, and being a part of this community. Any references and comments appreciated.</p> <hr> <p><strong>Edit #1</strong> (request for more information from the accepted answer):</p> <p><em>How does the main sketch trace through the C/C++ code?</em> </p> <p>For example, in the make file shown in the accepted answer: </p> <pre><code>$(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o </code></pre> <p><em>Does part of the main sketch transfer through in the compilation of malloc.c and realloc.c (as well as the c/c++ files)?</em> </p> <p>I would think so, being that it is compiled every time we change the main sketch.</p> <p><em>Lastly, how is the outputted .hex file uploaded to the board?</em> </p> <hr> <p><strong>Edit #2</strong> Trouble compiling with make method</p> <p>I am having issues with the manual compiling process, I am using <em>Arduino 1.6.5 r5</em>. It seems that <em>malloc.c</em> and <em>realloc.c</em> are not in the same place as they were in IDE 1.0.6.. Here is the makefile. </p> <pre><code># # Simple Arduino Makefile # # Author: Nick Gammon # Date: 18th March 2015 # # Edited by: Kyle Lawlor # Date: 30th October 2015 $H# where you installed the Arduino app ARDUINO_DIR = /home/wiz/programs/arduino-1.6.5-r5/ # various programs CC = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc" CPP = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++" AR = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar" OBJ_COPY = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy" # create a file called Blink.cpp in same base dir MAIN_SKETCH = Blink.cpp # compile flags for g++ and gcc # may need to change these F_CPU = 16000000 MCU = atmega328p # compile flags GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106 CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions CC_FLAGS = $(GENERAL_FLAGS) # location of include files INCLUDE_FILES = "-I$(ARDUINO_DIR)hardware/arduino/avr/cores/arduino" "-I$(ARDUINO_DIR)hardware/arduino/avr/variants/standard" # library sources LIBRARY_DIR = "$(ARDUINO_DIR)hardware/arduino/avr/cores/arduino/" build: $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o # $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o # $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o rm core.a # $(AR) rcs core.a malloc.c.o # $(AR) rcs core.a realloc.c.o $(AR) rcs core.a WInterrupts.c.o $(AR) rcs core.a wiring.c.o $(AR) rcs core.a wiring_analog.c.o $(AR) rcs core.a wiring_digital.c.o $(AR) rcs core.a wiring_pulse.c.o $(AR) rcs core.a wiring_shift.c.o $(AR) rcs core.a CDC.cpp.o $(AR) rcs core.a HardwareSerial.cpp.o $(AR) rcs core.a HID.cpp.o $(AR) rcs core.a IPAddress.cpp.o $(AR) rcs core.a main.cpp.o $(AR) rcs core.a new.cpp.o $(AR) rcs core.a Print.cpp.o $(AR) rcs core.a Stream.cpp.o $(AR) rcs core.a Tone.cpp.o $(AR) rcs core.a USBCore.cpp.o $(AR) rcs core.a WMath.cpp.o $(AR) rcs core.a WString.cpp.o $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex </code></pre> <p>The build fails unless the lines involving those two functions are commented out. I searched in the directories but had no luck in finding the libraries, so I decided to move forward in testing things out. </p> <p>Here is the file I am using as <em>Blink.cpp</em>.</p> <pre><code>#include &lt;Arduino.h&gt; void setup(){ pinMode(13, OUTPUT); } void loop(){ digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(13, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second } </code></pre> <p>Again, the <em>build does compile</em> ignoring <em>malloc</em> and <em>realloc</em>. I am unsure of whether these are critical libraries as I am not very familiar with C/C++. While the libraries do compile, <em>there is an error</em> derived from the <code>delay()</code> function in <em>Blink.cpp</em>.</p> <p>Here is that:</p> <pre><code>"/home/wiz/programs/arduino-1.6.5-r5/hardware/tools/avr/bin/avr-gcc" -Os -Wl,--gc-sections -mmcu=atmega328p -o Blink.cpp.elf Blink.cpp.o core.a -lm core.a(wiring.c.o): In function `delay': /home/wiz/programs/arduino-1.6.5-r5/hardware/arduino/avr/cores/arduino/wiring.c:113: undefined reference to `yield' collect2: error: ld returned 1 exit status make: *** [build] Error 1 </code></pre> <p>I am unsure at this point whether or not this error is related to the fact that <em>malloc</em> and <em>realloc</em> have not been compiled. I have traced back into the <em>wiring.c</em> file to find out where <code>yield()</code> was. That file starts with an <code>#include "wiring_private.h"</code> and here is the delay function and yield:</p> <pre><code>void delay(unsigned long ms) { uint16_t start = (uint16_t)micros(); while (ms &gt; 0) { yield(); if (((uint16_t)micros() - start) &gt;= 1000) { ms--; start += 1000; } } } </code></pre> <p>Here are the include statements from the <em>wiring_private.h</em> header. </p> <pre><code>#include &lt;avr/io.h&gt; #include &lt;avr/interrupt.h&gt; #include &lt;stdio.h&gt; #include &lt;stdarg.h&gt; #include "Arduino.h" </code></pre> <p>Perhaps on of these contain the <code>yield()</code> function, which is not being seen correctly?</p> <p>Does anyone have any advice for what I am doing wrong regarding building manually with 1.6.5? Any comments or further comments will be appreciated.</p> <hr> <p><strong>Edit #3</strong> Identified where <code>yield()</code> function is located.</p> <p><em>Project directory:</em></p> <pre><code>. ├── abi.cpp ├── Arduino.h ├── binary.h ├── Blink.cpp ├── Blink.cpp.d ├── Blink.cpp.o ├── CDC.cpp ├── CDC.cpp.d ├── CDC.cpp.o ├── Client.h ├── core.a ├── HardwareSerial0.cpp ├── HardwareSerial1.cpp ├── HardwareSerial2.cpp ├── HardwareSerial3.cpp ├── HardwareSerial.cpp ├── HardwareSerial.cpp.d ├── HardwareSerial.cpp.o ├── HardwareSerial.h ├── HardwareSerial_private.h ├── HID.cpp ├── HID.cpp.d ├── HID.cpp.o ├── hooks.c ├── IPAddress.cpp ├── IPAddress.cpp.d ├── IPAddress.cpp.o ├── IPAddress.h ├── main.cpp ├── main.cpp.d ├── main.cpp.o ├── new.cpp ├── new.cpp.d ├── new.cpp.o ├── new.h ├── Printable.h ├── Print.cpp ├── Print.cpp.d ├── Print.cpp.o ├── Print.h ├── run.mk ├── run.mk~ ├── Server.h ├── Stream.cpp ├── Stream.cpp.d ├── Stream.cpp.o ├── Stream.h ├── Tone.cpp ├── Tone.cpp.d ├── Tone.cpp.o ├── Udp.h ├── USBAPI.h ├── USBCore.cpp ├── USBCore.cpp.d ├── USBCore.cpp.o ├── USBCore.h ├── USBDesc.h ├── WCharacter.h ├── WInterrupts.c ├── WInterrupts.c.d ├── WInterrupts.c.o ├── wiring_analog.c ├── wiring_analog.c.d ├── wiring_analog.c.o ├── wiring.c ├── wiring.c.d ├── wiring.c.o ├── wiring_digital.c ├── wiring_digital.c.d ├── wiring_digital.c.o ├── wiring_private.h ├── wiring_pulse.c ├── wiring_pulse.c.d ├── wiring_pulse.c.o ├── wiring_pulse.S ├── wiring_shift.c ├── wiring_shift.c.d ├── wiring_shift.c.o ├── WMath.cpp ├── WMath.cpp.d ├── WMath.cpp.o ├── WString.cpp ├── WString.cpp.d ├── WString.cpp.o └── WString.h </code></pre> <p><code>yield()</code> is located in <em>hooks.c</em>. I do not understand why the function is not available to <em>wiring.c</em>.</p> <hr> <p><strong>Edit #4</strong> Compilation working</p> <p>Structure of <em>arduino-1.6.5-r5/hardware/arduino/avr/cores/arduino</em>:</p> <pre><code>. ├── abi.cpp ├── Arduino.h ├── binary.h ├── CDC.cpp ├── Client.h ├── HardwareSerial0.cpp ├── HardwareSerial1.cpp ├── HardwareSerial2.cpp ├── HardwareSerial3.cpp ├── HardwareSerial.cpp ├── HardwareSerial.h ├── HardwareSerial_private.h ├── HID.cpp ├── hooks.c ├── IPAddress.cpp ├── IPAddress.h ├── main.cpp ├── new.cpp ├── new.h ├── Printable.h ├── Print.cpp ├── Print.h ├── Server.h ├── Stream.cpp ├── Stream.h ├── Tone.cpp ├── Udp.h ├── USBAPI.h ├── USBCore.cpp ├── USBCore.h ├── USBDesc.h ├── WCharacter.h ├── WInterrupts.c ├── wiring_analog.c ├── wiring.c ├── wiring_digital.c ├── wiring_private.h ├── wiring_pulse.c ├── wiring_pulse.S ├── wiring_shift.c ├── WMath.cpp ├── WString.cpp └── WString.h </code></pre> <p>The reason the <code>yield()</code> function was not recognized was because I was not compiling with <em>1.6.5</em> correctly. Below is an updated <em>makefile</em> that compiles the <em>Blink.cpp</em> seemingly correct. I have yet to verify the sketch works on upload to the Arduino (via <code>avrdude</code>). The mistake was that I did not compile <code>abi.cpp</code>, <code>HardwareSerialx.cpp</code>(0-3), and <code>hooks.c</code>. <code>hooks.c</code> is where the <code>yield()</code> is located.</p> <p>Updated <em>makefile</em>:</p> <pre><code># # Simple Arduino Makefile # # Author: Nick Gammon # Date: 18th March 2015 # # Edited by: Kyle Lawlor # Date: 30th October 2015 $H# where you installed the Arduino app ARDUINO_DIR = /home/wiz/programs/arduino-1.6.5-r5/ # various programs CC = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc" CPP = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++" AR = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar" OBJ_COPY = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy" # create a file called Blink.cpp in same base dir MAIN_SKETCH = Blink.cpp # compile flags for g++ and gcc # may need to change these F_CPU = 16000000 MCU = atmega328p # compile flags GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106 CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions CC_FLAGS = $(GENERAL_FLAGS) # location of include files INCLUDE_FILES = "-I$(ARDUINO_DIR)hardware/arduino/avr/cores/arduino" "-I$(ARDUINO_DIR)hardware/arduino/avr/variants/standard" # library sources LIBRARY_DIR = "$(ARDUINO_DIR)hardware/arduino/avr/cores/arduino/" build: $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o # $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o # $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)hooks.c -o hooks.c.o $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)abi.cpp -o abi.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial0.cpp -o HardwareSerial0.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial1.cpp -o HardwareSerial1.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial2.cpp -o HardwareSerial2.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial3.cpp -o HardwareSerial3.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o rm core.a # $(AR) rcs core.a malloc.c.o # $(AR) rcs core.a realloc.c.o $(AR) rcs core.a hooks.c.o $(AR) rcs core.a WInterrupts.c.o $(AR) rcs core.a wiring.c.o $(AR) rcs core.a wiring_analog.c.o $(AR) rcs core.a wiring_digital.c.o $(AR) rcs core.a wiring_pulse.c.o $(AR) rcs core.a wiring_shift.c.o $(AR) rcs core.a abi.cpp.o $(AR) rcs core.a CDC.cpp.o $(AR) rcs core.a HardwareSerial.cpp.o $(AR) rcs core.a HardwareSerial0.cpp.o $(AR) rcs core.a HardwareSerial1.cpp.o $(AR) rcs core.a HardwareSerial2.cpp.o $(AR) rcs core.a HardwareSerial3.cpp.o $(AR) rcs core.a HID.cpp.o $(AR) rcs core.a IPAddress.cpp.o $(AR) rcs core.a main.cpp.o $(AR) rcs core.a new.cpp.o $(AR) rcs core.a Print.cpp.o $(AR) rcs core.a Stream.cpp.o $(AR) rcs core.a Tone.cpp.o $(AR) rcs core.a USBCore.cpp.o $(AR) rcs core.a WMath.cpp.o $(AR) rcs core.a WString.cpp.o $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex </code></pre> <p>Are <em>malloc.c</em> and <em>realloc.c</em> being used anymore? I searched across <em>1.6.5</em> for a directory similar to <em>avr-libc</em>, I couldn't find anything. I'm guessing they are no longer in use. </p> <hr> <p><strong>Edit #5</strong> Upload via <em>avrdude</em></p> <p>Basically this command worked for my board (Arduino Uno SMD):</p> <pre><code>avrdude -v -p atmega328p -c arduino -P /dev/ttyACM0 -b 115200 -D -U flash:w:/path/to/Blink.cpp.hex:i </code></pre> <p>This is all to say that the latter makefile in this post correctly builds the <em>.hex</em> file. Which can then successfully be uploaded onto the board. (Using Arduino 1.6.5).</p>
<blockquote> <p>I am interested in tracing through an upload process to learn more detail ...</p> </blockquote> <p>I covered the uploading process in some detail here: <a href="https://arduino.stackexchange.com/questions/15936/what-happens-when-code-is-uploaded-using-the-bootloader">What happens when code is uploaded using the bootloader?</a></p> <hr /> <blockquote> <p>I would like to understand which C-libraries are used</p> </blockquote> <p>See my post about <a href="https://arduino.stackexchange.com/questions/13178/classes-and-objects-how-many-and-which-file-types-i-actually-need-to-use-them">How the IDE organizes things</a></p> <hr /> <blockquote> <p>One example that I would like to see is an direct upload of C or C++ code without using the IDE gui.</p> </blockquote> <p>I wrote a simple Makefile on the <a href="http://forum.arduino.cc/index.php?topic=308853.msg2145054#msg2145054" rel="nofollow noreferrer">Arduino Forum</a>:</p> <pre><code># # Simple Arduino Makefile # # Author: Nick Gammon # Date: 18th March 2015 # where you installed the Arduino app ARDUINO_DIR = C:/Documents and Settings/Nick/Desktop/arduino-1.0.6/ # various programs CC = &quot;$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc&quot; CPP = &quot;$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++&quot; AR = &quot;$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar&quot; OBJ_COPY = &quot;$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy&quot; MAIN_SKETCH = Blink.cpp # compile flags for g++ and gcc # may need to change these F_CPU = 16000000 MCU = atmega328p # compile flags GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106 CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions CC_FLAGS = $(GENERAL_FLAGS) # location of include files INCLUDE_FILES = &quot;-I$(ARDUINO_DIR)hardware/arduino/cores/arduino&quot; &quot;-I$(ARDUINO_DIR)hardware/arduino/variants/standard&quot; # library sources LIBRARY_DIR = &quot;$(ARDUINO_DIR)hardware/arduino/cores/arduino/&quot; build: $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o rm core.a $(AR) rcs core.a malloc.c.o $(AR) rcs core.a realloc.c.o $(AR) rcs core.a WInterrupts.c.o $(AR) rcs core.a wiring.c.o $(AR) rcs core.a wiring_analog.c.o $(AR) rcs core.a wiring_digital.c.o $(AR) rcs core.a wiring_pulse.c.o $(AR) rcs core.a wiring_shift.c.o $(AR) rcs core.a CDC.cpp.o $(AR) rcs core.a HardwareSerial.cpp.o $(AR) rcs core.a HID.cpp.o $(AR) rcs core.a IPAddress.cpp.o $(AR) rcs core.a main.cpp.o $(AR) rcs core.a new.cpp.o $(AR) rcs core.a Print.cpp.o $(AR) rcs core.a Stream.cpp.o $(AR) rcs core.a Tone.cpp.o $(AR) rcs core.a USBCore.cpp.o $(AR) rcs core.a WMath.cpp.o $(AR) rcs core.a WString.cpp.o $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex </code></pre> <p>There are quite a few more complex ones around.</p> <hr /> <blockquote> <p>I want to see kind of the &quot;bare-minimum&quot; necessary for programming the Arduino (in C/C++).</p> </blockquote> <p>Here:</p> <pre><code>int main () { } </code></pre> <hr /> <blockquote> <p>Does part of the main sketch transfer through in the compilation of malloc.c and realloc.c (as well as the c/c++ files)?</p> <p>I would think so, being that it is compiled every time we change the main sketch.</p> </blockquote> <p>I'm not sure I understand the part about &quot;transfer through&quot; but basically functions which are needed in the main sketch are linked into the combined file by the linker.</p> <p>Effectively these are the main parts:</p> <pre><code># Compile main sketch $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o # Compile libraries $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o ... # Remove temporary &quot;combined libraries&quot; file rm core.a # Add compiled libraries into combined file &quot;core.a&quot; $(AR) rcs core.a malloc.c.o $(AR) rcs core.a realloc.c.o ... # Link main sketch to combined libraries (linker will discard things not needed) $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm # Make an .eep (EEPROM) file $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep # Make the main .hex file $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex </code></pre> <hr /> <blockquote> <p>Lastly, how is the outputted .hex file uploaded to the board?</p> </blockquote> <p>There are various ways of achieving this. The IDE calls the program <code>avrdude</code> which is designed to upload a .hex file to a processor. You can also just copy the .hex file to an SD card and upload it using a board programmer.</p> <hr /> <blockquote> <p>Are malloc.c and realloc.c being used anymore?</p> </blockquote> <p>They <strong>are</strong> being used, the trick is to find them.</p> <p>I can't see them being directly linked in a 1.6.5 compiler output, so I am assuming (I can't prove it right now) that they are linked in by default from libc.a (the default C library). Being a default library it is not mentioned on the linker line.</p> <p>In my (Linux) installation I found that library here:</p> <pre><code>~/Development/arduino-1.6.5-r5/hardware/tools/avr/avr/lib/libc.a </code></pre> <p>If you do a <code>nm</code> on it you find this (amongst other things):</p> <pre><code>malloc.o: 00000002 C __brkval U __do_clear_bss U __do_copy_data 00000002 C __flp 00000146 T free U __heap_end U __heap_start 00000000 T malloc 00000000 D __malloc_heap_end 00000002 D __malloc_heap_start 00000004 D __malloc_margin 0000003e a __SP_H__ 0000003d a __SP_L__ 0000003f a __SREG__ 00000000 a __tmp_reg__ 00000001 a __zero_reg__ </code></pre> <p>From <code>man nm</code>:</p> <pre><code> &quot;D&quot; &quot;d&quot; The symbol is in the initialized data section. ... &quot;T&quot; &quot;t&quot; The symbol is in the text (code) section. </code></pre> <hr /> <p>See <a href="http://www.linuxtopia.org/online_books/an_introduction_to_gcc/gccintro_17.html" rel="nofollow noreferrer">http://www.linuxtopia.org/online_books/an_introduction_to_gcc/gccintro_17.html</a> :</p> <blockquote> <p>The C standard library itself is stored in '/usr/lib/libc.a' and contains functions specified in the ANSI/ISO C standard, such as 'printf'---this library is linked by default for every C program.</p> </blockquote> <hr /> <p>I am guessing here that <code>malloc</code> and <code>free</code> moved into the standard (default) library since version 1.0.6 (or they wanted to override it with a bugfix) and it is now being found, by default, in the standard C library as described above.</p> <p>You should be able to find more about AVR libc at its page: <a href="http://www.nongnu.org/avr-libc/" rel="nofollow noreferrer">http://www.nongnu.org/avr-libc/</a></p>
17224
|arduino-yun|
How to access parse cloud functions using arduino?
2015-10-27T13:10:13.533
<p>I have created rest service using .js file on Parse.com. I want to access cloud function from arduino.</p> <p>i tried this </p> <p>client.get(<a href="https://myAppID:javascript-key=myJavaScriptKey@api.parse.com/1/functions/hello" rel="nofollow">https://myAppID:javascript-key=myJavaScriptKey@api.parse.com/1/functions/hello</a>");</p> <p>i am getting error "Method not allowed".</p> <p>Solution : Somehow i got the answer which is as follows.I hope it will help others.</p> <pre><code> ParseCloudFunction cloudFunction; cloudFunction.setFunctionName(function_name); //string ("hello") cloudFunction.add("light_sensor", light); //pass parameter to cloud ParseResponse response = cloudFunction.send(); Serial.println(response.getJSONBody()); </code></pre>
<p>I read api of Parse and there i got the class to call cloud function from Arduino.I hope it will help others.</p> <pre><code> ParseCloudFunction cloudFunction; cloudFunction.setFunctionName(fnname); //String ("hello") cloudFunction.add("light_sensor", 139); //parameter ParseResponse response = cloudFunction.send(); Serial.println(response.getJSONBody()); </code></pre>
17226
|arduino-due|digital-analog-conversion|
Are DAC pins useful for anything besides working with audio?
2015-10-27T14:08:22.237
<p>Whenever I run into information about DAC, it seems to be related to audio processing. Are there any other use cases where DAC might be useful, or have any advantages over regular ADC PWM output on an Arduino?</p>
<p>They are incredibly useful. They are essentially how you deal with the analog world.</p> <p>For example, I'm using two of them in a project here that uses a frequency generator and a couple of op-amps to create a VSWR bridge, allowing me to figure out the resonant frequencies of an antenna... The parts with the arduino cost less than $20... Buying something that does the same thing is about $300!</p> <p>So, yes, they are very useful. :)</p>
17234
|data-type|
Cast from long to int
2015-10-27T16:14:02.517
<p>How does arduino uno cast from <strong>long</strong> to <strong>int</strong>?</p> <p>Does it truncate the bits? (Does it just delete the 16 most left bits?)</p>
<p>Yes, it just blindly chops off the upper 16 bits. That means that the sign can change between the two.</p> <p>For instance, 123456789 gets truncated to -13035 and -123456789 truncates to 13035.</p> <p>To see that in more detail, look at the binary. 123456789 in binary is:</p> <pre><code>0000 0111 0101 1011 1100 1101 0001 0101 </code></pre> <p>Truncate that at 16 bits and you get:</p> <pre><code>1100 1101 0001 0101 </code></pre> <p>And of course the high (sign) bit is set, so the value is negative.</p>
17239
|home-automation|
Accuracy of liquid level measurement using sonar sensor
2015-10-27T19:12:39.507
<p>Is it a good way to measure liquid level in a water tank using a general purpose sonar sensor? How can echoes from the tank walls affect measurement accuracy?</p> <p>I have a cylinder shaped <strong>horizontal</strong> 700L water tank, used for emergency water supply. I need to measure the water level with approx. 5% accuracy and display it in my kitchen. </p> <p><a href="https://i.stack.imgur.com/0XD5H.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0XD5H.jpg" alt="sonar sensor"></a></p> <p><strong>UPDATE! Today I found this helpful page: <a href="http://alaskanshade.blogspot.ch/2013/12/home-heating-hacking-part-1-or-how-to.html" rel="nofollow noreferrer">Home Heating Hacking Part 1 or How to Measure an Oil Tank</a>. I had no time to realize my idea, but it's exactly what I wanted to do. So take a look.</strong></p>
<p>I've implemented this on my 2 x 23,000 litre water tanks using 2x hc-sr04 sensors mounted on the tank lids and a nano in the pump house. Yes water is a good hard reflective surface to bounce the ultrasonic sound waves off. My tanks have an overflow outlet but not sure how well the eletronic will last? However they are cheap to replace. It is only early days but the overall the results are looking good. Couple of points:</p> <p>1.polling occurs hourly. </p> <p>2.I only power the ultrasonic sensor just before taking a reading.</p> <p>3.Has a sound detection sensor to alert on water pump overrun, ie a leak.</p> <p>good luck </p>
17243
|arduino-leonardo|can-bus|
Can BUS Shield on Arduino Leonardo - Can't init CAN
2015-10-27T23:53:37.957
<p>I'm hoping to get some help with this as I am unable to get the CAN to Initialize.</p> <p>I have the sparkfun Can-Bus shield: <a href="https://www.sparkfun.com/products/13262" rel="nofollow">https://www.sparkfun.com/products/13262</a></p> <p>and an Arduino Leonardo board.</p> <p>I'm using the following code to try to connect my 2008 Audi S6 to the Arduino board:</p> <pre><code>#include &lt;Canbus.h&gt; #include &lt;defaults.h&gt; #include &lt;global.h&gt; #include &lt;mcp2515.h&gt; #include &lt;mcp2515_defs.h&gt; #include &lt;Canbus.h&gt; char UserInput; int data; char buffer[456]; //Data will be temporarily stored to this buffer before being written to the file //********************************Setup Loop*********************************// void setup(){ Serial.begin(9600); while(!Serial); Serial.println("CAN-Bus Demo"); if(Canbus.init(CANSPEED_500)) /* Initialise MCP2515 CAN controller at the specified speed */ { Serial.println("CAN Init ok"); } else { Serial.println("Can't init CAN"); } delay(1000); Serial.println("Please choose a menu option."); Serial.println("1.Speed"); Serial.println("2.RPM"); Serial.println("3.Throttle"); Serial.println("4.Coolant Temperature"); Serial.println("5.O2 Voltage"); Serial.println("6.MAF Sensor"); } //********************************Main Loop*********************************// void loop(){ while(Serial.available()){ UserInput = Serial.read(); if (UserInput=='1'){ data=Canbus.ecu_req(VEHICLE_SPEED, buffer); Serial.print("Vehicle Speed: "); Serial.print(data); Serial.println(" km/hr "); delay(1000); } else if (UserInput=='2'){ data= Canbus.ecu_req(ENGINE_RPM, buffer); Serial.print("Engine RPM: "); Serial.print(data); Serial.println(" rpm "); delay(1000); } else if (UserInput=='3'){ data= Canbus.ecu_req(THROTTLE, buffer); Serial.print("Throttle: "); Serial.print(data); Serial.println(" %% "); delay(1000); } else if (UserInput=='4'){ data =Canbus.ecu_req(ENGINE_COOLANT_TEMP, buffer); Serial.print("Engine Coolant Temp: "); Serial.print(data); Serial.println(" degC"); delay(1000); } else if (UserInput=='5'){ data=Canbus.ecu_req(O2_VOLTAGE, buffer); Serial.print("O2 Voltage: "); Serial.print(data); Serial.println(" V"); delay(1000); } else if (UserInput=='6'){ data=Canbus.ecu_req(MAF_SENSOR, buffer); Serial.print("MAF Sensor: "); Serial.print(data); Serial.println(" g/s"); delay(1000); } else { Serial.println(UserInput); Serial.println("Not a valid input."); Serial.println("Please enter a valid option."); } } } </code></pre> <p>Overall, I just can't get the CAN to initialize. I've looked online and just can't seem to find a solid solution. I've tried other libraries as well to no avail.</p> <p>Please assist!</p>
<p>Increasing that delay in the MCP2515.c file also fixed this issue for me. I am running the sparkfun Can-Bus shield on an Arduino pro-mini, and here is my serial monitor output before the change, and after:</p> <p>12:56:38.580 -&gt; CAN Read - Testing receival of CAN Bus message 12:56:39.556 -&gt; Can't init CAN 13:01:40.992 -&gt; CAN Read - Testing receival of CAN Bus message 13:01:42.016 -&gt; CAN Init ok</p>
17249
|robotics|
How to switch program in arduino using android app?
2015-10-28T07:34:49.490
<p>I have 2 programs made for my arduino.The first one is for solving a maze automatically and the second one is for controlling the robot with a android app.I wanted to control the robot with the app I made as soon as it has finished solving the maze. Is it possible to upload both the program in the arduino and run it one at a time?If so can you tell me how? </p>
<p>Once I made a sketch to run multiple programs. I wrote a <code>setup</code> and <code>loop</code> function for every different "program", (e.g. <code>setup_p1</code>, <code>setup_p2</code>, ... <code>loop_p1</code>, ...) and then wrote a simple <code>main</code> sketch to handle them all.</p> <p>In my application I choose the program at startup with a 3-dipswitch, but you can easily switch this to allow "on the fly" switching.</p> <p>I choose to use a callback because it's faster than just checking the mode every time, at least in my case</p> <pre><code>// callback for loop function typedef void (*loopfunction)(); loopfunction currentloop; void setup() { // Set dip-switch pins as input pinMode(MODE_PIN2,INPUT_PULLUP); pinMode(MODE_PIN1,INPUT_PULLUP); pinMode(MODE_PIN0,INPUT_PULLUP); // Concatenate the dip-switch values byte mode = 7 - ((digitalRead(MODE_PIN2) &lt;&lt; 2) | (digitalRead(MODE_PIN1) &lt;&lt; 1) | digitalRead(MODE_PIN0)); // choose the correct mode switch(mode) { case 0: // Shutdown - do nothing break; case 1: // Program 1 setup_p1(); currentloop = loop_p1; break; case 2: // Program 2 setup_p2(); currentloop = loop_p2; break; ... } // Not a valid program: halt if (!currentloop) { while(1); } } void loop() { // Execute the current loop currentloop(); } </code></pre>
17259
|arduino-uno|programming|compile|
Can anyone explain how this code can be converted to work on a Arduino Uno
2015-10-28T15:54:34.470
<p>I was hoping someone could help, im totally new to this. I wish to use this code for a Raspberry Pi on an Arduino Uno with the Adafruit SD data logging shield. It is for recording reed switch closures on a tipping bucket rain gauge. The interrupt and bounce time are to allow program interrupts and false tip suppression. I am looking to tie it in with the RTC and SD storage options on the Arduino. Any help appreciated.</p> <pre><code>#!/usr/bin/python3 import RPi.GPIO as GPIO import time # this many mm per bucket tip CALIBRATION = 0.200 # which GPIO pin the gauge is connected to PIN = 17 # file to log rainfall data in LOGFILE = "log.csv" GPIO.setmode(GPIO.BCM) GPIO.setup(PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) # variable to keep track of how much rain rain = 0 # the call back function for each bucket tip def cb(channel): global rain rain = rain + CALIBRATION # register the call back for pin interrupts GPIO.add_event_detect(PIN, GPIO.FALLING, callback=cb, bouncetime=300) # open the log file file = open(LOGFILE, "a") # display and log results while True: line = "%i, %f" % (time.time(), rain) print(line) file.write(line + "\n") file.flush() rain = 0 time.sleep(5) # close the log file and exit nicely file.close() GPIO.cleanup() </code></pre>
<p>This should help get you started but don't expect it to actually work as it is. Note that i did not test this at all, it's for example purposes. if there is a specific programming problem it should be addressed separately instead of handing out working code. </p> <pre><code>const int CALIBRATION = 0.200; //Calibration Constant int pin = 2; //Pin it's on, this is int0 for uno. volatile int rain = 0; //Used in interrupt routine void setup() { Serial.begin(9600); pinMode(pin, INPUT); attachInterrupt(digitalPinToInterrupt(pin), cn, FALLING); } void loop() { /* Output OR LOG DATA HERE Also You need a Time Library and RTC (Real Time CLock) the above code is for a raspberry pi that has all that. */ } void cb() { rain = rain + CALIBRATION; } </code></pre>
17264
|c++|
Is there a way to use functions defined in a library in any class?
2015-10-28T19:15:12.947
<p>I'm trying to design a menu interface on a 1.8'' TFT display module. I've got it working with the Adafruit_ST7735 + Adafruit_GFX libraries. At least when I was just trying out the features... But now I'm trying to organize the code in Classes as this thing will get too complex soon. I have done some Java and C, so I started learning C++. I've been reading and coding nonstop for a week now, but there are some things that I can't wrap my head around that keep me from making any progress for a couple of days already.</p> <p>So... For example there's a function public void drawRect(); in Adafruit_ST7735 library and I have a function draw() that draws a bunch of related stuff to the display in my own class (Rectangle.cpp). Say I initialize the display in my main program file how can I use that drawRect() function in my Rectangle::draw()?</p> <p>Also Rectangle will be used for composing other parts of the menu interface and will probably be initialized in a collection or as a member of another class. </p> <p>I've tried a bunch of different things but I've come to a dead end.</p> <p>EDIT:</p> <p>main program:</p> <pre><code>#include "_v0_0_0.h" #include &lt;Adafruit_GFX.h&gt; // Core graphics library #include &lt;Adafruit_ST7735.h&gt; // Hardware-specific library #include &lt;SPI.h&gt; #include "Point.h" #include "Rectangle.h" #include "SomeView.h" #define TFT_CS 4 #define TFT_RST 0 #define TFT_DC 10 Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST); SomeView a_view; void setup() { tft.initR(INITR_BLACKTAB); // initializes the display } void loop() { a_view.draw(); //draw something to view (a button, scrollbar, menu item, etc) while (true) {} } </code></pre> <p>SomeView.h:</p> <pre><code>#include "Rectangle.h" class SomeView { private: Rectangle a_rectangle; public: SomeView(); void draw(); const Rectangle&amp; getRectangle() const { return a_rectangle; } void setRectangle(const Rectangle&amp; rectangle) { a_rectangle = rectangle; } }; </code></pre> <p>SomeView.cpp:</p> <pre><code>#include "SomeView.h" SomeView::SomeView() : a_rectangle(Point::Point(0, 0), Point::Point(0, 0)) { } void SomeView::draw() { a_rectangle.setCorners(Point::Point(0, 0), Point::Point(2, 6)); a_rectangle.draw(); a_rectangle.setCorners(Point::Point(20, 66), Point::Point(100, 100)); a_rectangle.draw(); } </code></pre> <p>Rectangle.h:</p> <pre><code>#include "Point.h" #include &lt;Adafruit_GFX.h&gt; // Core graphics library #include &lt;Adafruit_ST7735.h&gt; // Hardware-specific library #include &lt;SPI.h&gt; class Rectangle{ private: Point p1; Point p2; public: Rectangle(); Rectangle(Point&amp; p1, Point&amp; p2); void setCorners(const Point&amp; p1, const Point&amp; p2); void draw(); // ... getters and setters for the points }; </code></pre> <p>Rectangle.cpp:</p> <pre><code>#include "Rectangle.h" Rectangle::Rectangle() : p1(), p2() { } Rectangle::Rectangle(Point&amp; p1, Point&amp; p2) : p1(p1), p2(p2) { } void Rectangle::setCorners(const Point&amp; p1, const Point&amp; p2) { this-&gt;p1 = p1; this-&gt;p2 = p2; } // this is where I want to use a function from the adafruit library void Rectangle::draw() { Adafruit_ST7735::drawRect(p1.getX(), p1.getY(), p2.getX(), p2.getY(), ST7735_GREEN); } </code></pre>
<p>There are two basic methods to do what you want:</p> <ol> <li>Inheritance</li> <li>Pointer passing</li> </ol> <p>Inheritance involves making your new class a <em>child</em> class of the Adafruit TFT class. You new class then gets all the public functions of the Adafruit class - it essentially becomes the Adafruit class <em>plus</em> your extra functions overlaid over the top:</p> <pre><code>class Rectangle : public Adafruit_ST7735 { ... }; </code></pre> <p>You have to ensure that you provide a suitable constructor that passes the right parameters to the Adafruit parent class, and then you create a Rectangle class <em>instead</em> of the Adafruit class in your sketch.</p> <ul> <li>Inheritance tutorial: <a href="http://www.cplusplus.com/doc/tutorial/inheritance/" rel="nofollow">http://www.cplusplus.com/doc/tutorial/inheritance/</a></li> </ul> <p>That is fine if you just want one class that uses the functions from the Adafruit class. The second option is to pass a pointer (or reference) to the Adafruit class to your other classes, either when you construct them or at function call time. For instance, you might have:</p> <pre><code>class Rectangle { private: Adafruit_ST7735 *_tft; public: Rectangle(Adafruit_ST7735 &amp;tft) : _tft(&amp;tft) {} }; </code></pre> <p>Then in your function you can use:</p> <pre><code>void Rectangle::draw() { _tft-&gt;drawRect(p1.getX(), p1.getY(), p2.getX(), p2.getY(), ST7735_GREEN); } </code></pre> <p>You would, of course, construct your class with:</p> <pre><code>Adafruit_ST7735 myTFTScreen(blah blah blah); Rectangle myRect(myTFTScreen); </code></pre> <p>Then call <code>myRect.draw();</code>.</p>
17270
|i2c|
What is the purpose of the howMany integer in the wire.onReceive() function from the example code?
2015-10-28T21:41:42.313
<p>In the master write/ slave read example for the wire library, there is an integer declared howMany that is never used.</p> <pre><code> void setup() { Wire.begin(8); // join i2c bus with address #8 Wire.onReceive(receiveEvent); // register event Serial.begin(9600); // start serial for output } void receiveEvent(int howMany) { while (1 &lt; Wire.available()) { // loop through all but the last char c = Wire.read(); // receive byte as a character Serial.print(c); // print the character } int x = Wire.read(); // receive byte as an integer Serial.println(x); } </code></pre> <p>As the function does not work without it, i would like to know what is its exact purpose.I would imagine that is something regarding the buffer size.</p>
<p>The reference page <a href="https://www.arduino.cc/en/Reference/WireOnReceive" rel="nofollow noreferrer">https://www.arduino.cc/en/Reference/WireOnReceive</a> states:</p> <blockquote> <p>Parameters</p> <p>handler: the function to be called when the slave receives data; this should take a single int parameter (the number of bytes read from the master) and return nothing, e.g.: <code>void myHandler(int numBytes)</code></p> </blockquote> <p>I suggest you look at the reference pages for the functions in future before asking what they do.</p>
17275
|arduino-uno|ethernet|relay|
Relay doing opposite to digital pin
2015-10-28T23:42:57.620
<p>I have a Arduino UNO with a Ethernet shield which hosts a basic HTML page with a button on it which controls a Relay module.</p> <p>I'm trying to connect to a computer's power button so I can turn it on remotely.</p> <p>I have found out that the relay basically does the opposite to the digital pin's output</p> <p>Normally open Relay <br> HIGH = Open <br> LOW = Closed</p> <p>I connected it through a NOT Gate made using a NPN transistor and it works perfectly how I wanted it.</p> <p>Now to the question... Is there a way to write the code to make the digital pin = HIGH straight away and fast enough to not allow the relay to close the circuit and accidentally turn the computer on/off when the Arduino restarts, so I don't have to use a NOT Gate.</p>
<p>Try This:</p> <pre><code>const On = LOW; // For non inverted logic swap on and off. const Off = HIGH; const pump = 5; void setup() { pinMode(pump, OUTPUT); // sets the digital pin 13 as output } digitalWrite(pump, On); digitalWrite(pump, Off); </code></pre>
17282
|c++|library|class|float|
Problem assign float to an embed class within the Linked-list libary
2015-10-29T09:03:55.460
<p>I have successfully implemented some code which uses a linked-list. Everything is working, except assigning a value to a float within the embeded class. When I run the code below, I get the expected behavior, a flashing LED for 10 secs then LED turns continuously ON, and I also get the debug messages I expect. However, when I comment the marked line to assign a value to the float, it still compiles, but the LED does not flash as expected and I get complete rubbish from debug. I am using codebender on Chrome, and I have tried Firefox (both given same results).</p> <p>Main Sketch <a href="https://codebender.cc/sketch:175995" rel="nofollow">https://codebender.cc/sketch:175995</a></p> <p>Example of library working <a href="https://codebender.cc/sketch:176008" rel="nofollow">https://codebender.cc/sketch:176008</a></p> <p>Can anyone help?</p> <pre><code>typedef void(*GF)(void); #include "LinkedList.h" class CsC { public: float PerS; GF FunctionToCall; }; LinkedList&lt;CsC*&gt; TaskList = LinkedList&lt;CsC*&gt;(); void LEDON() { digitalWrite(13,HIGH); } void after(float interval, String intervalDescription, GF func); void after(float interval, String intervalDescription, GF func) { float multi = 1; if(intervalDescription == "mins") multi *= 60; float delayMS = multi * interval; CsC *c; //Error if either of these lines uncommented //c-&gt;PerS=10000; //c-&gt;PerS=delayMS; c-&gt;FunctionToCall=func; TaskList.add(c); Serial.print("."); } void setup() { Serial.begin(9600); pinMode(13, OUTPUT); Serial.println("Start write task list"); after(35,"secs",LEDON); Serial.println("Done"); Serial.println("Start prog"); } void loop() { Serial.print("List="); Serial.print(TaskList.size()); while(TaskList.size()&gt;0){ CsC *c=TaskList.shift(); long timeout=millis()+10000; //long timeout=millis()+((long)(c-&gt;PerS*1000.0)); while(millis()&lt;timeout){ //To indicate it is running, and to save time, I have used a delay here digitalWrite(13,HIGH); delay(250); digitalWrite(13,LOW); delay(250); } c-&gt;FunctionToCall(); } Serial.print("."); Serial.println("complete"); while(1){} } </code></pre>
<p>One possible error is a memory leak as you did not allocate the memory to the class Try</p> <pre><code>CsC *c=new CsC(); </code></pre>
17296
|arduino-uno|spi|adc|
Interfacing ADS8319 with Arduino UNO
2015-10-29T15:35:48.577
<p>I am using Arduino UNO and trying to interface 2 16-bit <a href="http://www.ti.com/lit/ds/symlink/ads8319.pdf" rel="nofollow noreferrer">ADS8319</a> ADCs with it via the SPI interface.</p> <p>I have interfaced the 2 ADCs with the micro-controller using the "4 Wire CS Mode Without Busy Indicator" (data sheet page number 15). </p> <p>I am using the following code to get the values from the ADCs.</p> <pre class="lang-c prettyprint-override"><code>#include &lt;SPI.h&gt; #define CONVPIN 7 #define SELPIN 8 #define SELPIN2 4 #define MISOPIN 12 #define SCLKPIN 13 int adcvalue; byte byte1; byte byte2; const float aRefVoltage = 5; float volts = 0; void setup() { // put your setup code here, to run once: pinMode(SELPIN, OUTPUT); // ADC's selection pin pinMode(SELPIN2, OUTPUT); // 2nd ADC's selection pin pinMode(CONVPIN, OUTPUT); // ADC's conversion pin pinMode(SCLKPIN, OUTPUT); // ADC's clock pin pinMode(MISOPIN, INPUT); // ADC's data out SPI.begin(); Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: digitalWrite(CONVPIN, LOW); digitalWrite(SELPIN, HIGH); digitalWrite(SELPIN2, HIGH); digitalWrite(CONVPIN, HIGH); digitalWrite(SELPIN, LOW); delay(1000); byte1 = SPI.transfer(0x00); //transfer (read) 8 bits from the adc chip D15-8 byte2 = SPI.transfer(0x00); //transfer (read) the second 8 bits. D7-0 adcvalue = (byte1 &lt;&lt;8) | (byte2 &amp; 0xff); // combine the 2 bytes to make our 16 bit word Serial.print("Voltage Value: "); Serial.println(adcvalue,BIN); volts = (adcvalue*aRefVoltage/65535); Serial.print(" Sensor Volts: "); Serial.println(volts,5); delay(1000); } </code></pre> <p>However i am not getting the right values. The ADC that ive selected by "digitalWrite(SELPIN, LOW);" should output 1V, whereas the values keep on changing in between 0 and 2.2 V .I am not sure if my code is correct or not. Can you please verify the code so that i should know whether the problem is in my hardware, or the code.</p> <p>Below is the screenshot for my schematic :</p> <p><a href="https://i.stack.imgur.com/jb2d8.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jb2d8.jpg" alt="enter image description here"></a></p> <p>Your helpful suggestions and comments would be appreciated ! Thankyou.</p>
<p>After lots and lots and changing values for resistors and capacitors and checking connections, i came to find out that my micro-controller ground was not at the same level as the ADCs ( i had already connected its ground with my circuit board ground but there was some kind of problem ). When i soldered the controllers ground just near the ADCs ground, both the ADCs started working properly.</p>
17299
|arduino-uno|sensors|sketch|temperature-sensor|
TMP36 probe reading 0 on analog
2015-10-29T17:26:34.257
<p>I've designed this system which is supposed to turn on the LEDs when the temperature of a particular probe exceeds 32 degrees. From what I can tell, this should be functional but the analog sensor is always reading 0 when calling analogRead() on the pin. </p> <p>Here is an image of my circuit:</p> <p><a href="https://i.stack.imgur.com/TiksO.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TiksO.jpg" alt="enter image description here"></a></p> <p>and my code:</p> <pre><code>int length = 5; float airTemp = 32; void setup() { Serial.begin(9600); } void loop() { // loads current temperature into array int reading; float voltage; float temp[length]; for (int i = 0; i &lt; length; i++) { reading = analogRead(i); Serial.print(reading); voltage = reading * 5.0; voltage /= 1024; temp[i] = (voltage - 0.5) * 100; } // turns on/off fans based on current temperature for (int i = 0; i &lt; length; i++) { pinMode(i, OUTPUT); if (temp[i] &gt; airTemp) { digitalWrite(i + 8, HIGH); } else if(temp[i] &lt;= airTemp) { digitalWrite(i + 8, LOW); } } delay(1000); } </code></pre> <p>I learned how to read the temperature from <a href="https://learn.adafruit.com/tmp36-temperature-sensor/using-a-temp-sensor" rel="nofollow noreferrer">here</a>. It's probably a dumb mistake, but I just started working with Arduino yesterday and I couldn't find information anywhere so thanks in advance.</p>
<p>The image on the linked tutorial has the middle pin of the TMP036 going to the analog input, whereas you have it going to 5V, so that is not going to help one bit.</p> <p>In other words, it is wired wrongly.</p>
17301
|arduino-mega|motor|pwm|robotics|
Linear actuator jitters/vibrates when getting PWM from Arduino Mega 2560 through JKR 21v3 motor controller
2015-10-29T17:50:13.783
<p>I recently bought this linear actuator and motor controller from Pololu:</p> <ul> <li><p><a href="https://www.pololu.com/product/2305" rel="nofollow">Linear actuator</a></p></li> <li><p><a href="https://www.pololu.com/product/1394" rel="nofollow">Motor Controller JRK21v3</a></p></li> </ul> <p>There are several steps that I have to follow in order to set this thing up before I can test it. These instructions can be found here: <a href="http://www.pololu.com/docs/0J38/5" rel="nofollow">Pololu JRK USB Motor Controller User’s Guide » Setting Up Your System</a></p> <p>I would like to program this using PWM method because I would like to keep the Serial RX for other sensors. From my little experiment, by using a potentiometer, I noticed this pattern:</p> <p>Position: Voltage </p> <ol> <li>Fully extended : 0 V</li> <li>At Rest : 2.35V</li> <li>Fully Retracted : 4.77V.</li> </ol> <p>For this system, I will be controlling it using a PS2 controller. So, by using only the Y_axis of the analog joystick of a PS2 Controller (Up: 0, Rest: 128 and Down: 255), I program it as follows:</p> <pre class="lang-c prettyprint-override"><code>//Move Linear Actuator with PS2 on JRK21v3 Controller #define pwm 6 //red wire #define dir 7 //yellow wire //PS2 controller #include &lt;SoftwareSerial.h&gt; #include &lt;Cytron_PS2Shield.h&gt; Cytron_PS2Shield ps2(10, 11); // SoftwareSerial: Rx and Tx pin void setup() { pinMode(pwm,OUTPUT); ps2.begin(9600); Serial.begin(9600); } void loop() { int Y_axis = ps2.readButton(PS2_JOYSTICK_RIGHT_Y_AXIS); // 0 - 255 Serial.print("Y_axis:"); Serial.println(Y_axis); analogWrite(pwm, Y_axis); } </code></pre> <p>When I tested it, the linear actuator jitters/vibrates when it is at rest position. What could possibly cause this? Is it the duty cycle due to the PWM? How can I fix this or are there any other better methods?</p>
<p>I got this working using the <a href="https://www.arduino.cc/en/Reference/Servo" rel="nofollow">Servo library</a>. </p> <ul> <li>You set the input method to PWM.</li> <li>Connect your RX on the motor controller and hook it up to the servo pin.</li> <li>Connect the ground of the Arduino to the ground of the JRK 21v3.</li> <li>Then use the <a href="https://www.arduino.cc/en/Tutorial/Knob" rel="nofollow">knob servo sample</a> by hooking up a pot to a Arduino.</li> <li>The calibrate the JRK 21v3 by selecting learn.</li> </ul> <p>Now you can use the actuator as a servo.</p>
17303
|hardware|communication|electronics|
Gain on a receiver
2015-10-29T18:02:04.400
<p>I'm doing a project on the arduino with simple 433MHz antenna modules. And I was wondering if someone could offer clarifications on how receivers work. </p> <p>I read that high gain receivers can pick up a very narrow beam of radio power and thus, can transfer data at high rates. Given that this signal is tightly focused to the transmitting end. </p> <p>And a low gain receiver can pick up a much wider beam of radio power.</p> <p>My question is the following. When they say "narrower beam" does that represent the amplitude of the signal or the number of different waves that are being transmitted? OR does it refer to the number of DIFFERENT frequencies it can pick up? Sorry, if my question is confusing. Happy to clarify any part of it. </p> <p>My Source: <a href="http://www.qrg.northwestern.edu/projects/vss/docs/communications/2-what-are-high-and-low-gain.html" rel="nofollow">http://www.qrg.northwestern.edu/projects/vss/docs/communications/2-what-are-high-and-low-gain.html</a></p>
<p>Think of the receiver as a camera with a telephoto lens.</p> <p>With the lens zoomed out you can see a large area. You get visual information from all over.</p> <p>With the lens zoomed in you can only see a very small area. The visual information you receive is only from a very small <em>field of vision</em> and things outside that field never get to you.</p> <p>It's exactly the same with radio waves except that the shape of the antenna affects the zoom instead of lenses.</p>
17309
|arduino-uno|softwareserial|
Read function in Software Serial
2015-10-29T19:18:48.343
<p>I have a question regarding how the read function works in Software Serial.</p> <p>recv reads the bits a receiver picks up into a serial buffer. than read returns a uint8_t. However, when i set read() equal to a variable and print it, it doesn't necessarily always print out a byte. For instance: int x = rx.read(); //if the read is supposed to read 60, x prints 111100 int x = rx.read(); //if the read is supposed to read 226, x prints 11100010</p> <p>How come the first statement doesn't print 00111100? </p> <p>Sorry, i realize this might be a very dumb question. I looked into the software serial library, and couldn't identify what I'm missing. </p>
<p>For the very same reason that you don't normally write 00000069 instead of just 69. The leading 0's are completely meaningless and can be omitted or included without any change to the value.</p>
17326
|arduino-uno|communication|softwareserial|
Synchronization and Implementing hamming code on Software Serial
2015-10-30T03:23:34.807
<p>I want to learn and use Hamming Code. Would it be wise to alter the Software serial library to do this or just change the data being transmitted in the actual Arduino sketch? </p> <p>Also, for means of better synchronization, what would be the best method with regards to <a href="http://rayshobby.net/cart/image/cache/data/acc/rf_pair-500x500.JPG" rel="nofollow">these</a> tx/rx modules working with the Arduino using Software Serial. Am I constrained to using the built in synchronization from the library or may I also implement other forms of synchronization, like manchester and NRZ coding? If so, any guidance here? </p> <p><strong>EDIT</strong></p> <p>For implementing Hamming code, what if the interference occurs on the parity bit? Is there a way around this problem? </p>
<p>Could look something like this:</p> <pre><code>class HammingStream : public Stream { public: HammingStream(Stream&amp; ios) : m_ios(ios) {} virtual size_t write(uint8_t byte); virtual int read(); virtual int available(); virtual void flush(); protected: Stream&amp; m_ios; uint8_t encode4(uint8_t nibble); uint8_t decode8(uint8_t code); }; size_t HammingStream::write(uint8_t byte) { m_ios.write(encode4(byte &gt;&gt; 4)); m_ios.write(encode4(byte &amp; 0xf)); return (1); } int HammingStream::read() { if (available() == 0) return (-1); uint8_t nibble = decode8(m_ios.read()); return ((nibble &lt;&lt; 4) | decode8(m_ios.read()); } int HammingStream::available() { return (m_ios.available() / 2); } void HammingStream::flush() { m_ios.flush(); } </code></pre> <p>Then you could:</p> <pre><code>HammingStream HammingSerial(SoftwareSerial); HammingSerial.println(F("hello world")); </code></pre> <p>The above leaves out the encoding/decoding but also error detection. Hamming decoding can capture up to two bit errors and do one bit correction (on 4-bit data).</p> <p>An example of implementation of the <a href="https://github.com/mikaelpatel/Cosa/blob/master/libraries/HammingCodec_8_4/HammingCodec_8_4.hh" rel="nofollow">coder</a> may be found in Cosa. Here Hamming(8, 4) is used to improve VirtualWire performance. Please note that the coder table is adjusted for RF and avoiding DC signal (i.e. long periods of zero or one). </p> <p>Cheers!</p>
17329
|arduino-uno|1-wire|
Please explain this OneWire communication with Arduino Uno and DS2502-E48
2015-10-30T08:39:36.443
<p>The goal is to read the MAC address from a <a href="http://pdfserv.maximintegrated.com/en/ds/DS2502-E48.pdf" rel="nofollow">DS2502-E48 </a>chip.</p> <p>I think I accomplished this goal too with the following code, but I can't get behind at how this works. I had a similar program with a PIC chip as reference.</p> <p>I checked several references about OneWire and the DS2502 but not the info I needed to hop to the right memory addresses. Where'd I normally attain the information so that I know I have to write: <strong>cc ,f0 , 0, 10</strong> , read a <em>random</em> byte, and then I'm at the right position for MAC.</p> <pre><code>#include &lt;OneWire.h&gt; OneWire ds(2); void setup() { Serial.begin(9600); byte i; byte dataLength; byte present = 0; byte data[12]; byte addr[8]; if ( !ds.search(addr)) { Serial.print("No more addresses.\n"); ds.reset_search(); delay(250); return; } ds.reset(); ds.select(addr); delay(1000); // maybe 750ms is enough, maybe not present = ds.reset(); if (present != 1 ) { Serial.println("No device present, exiting..."); return; } ds.write(0xCC);//SKIP_ROM ds.write(0xF0);//READ_MEMORY ds.write(0); // ? ds.write(10); // ? ds.read(); // ? dataLength = ds.read(); for ( i = 0; i &lt; dataLength; i++) { data[i] = ds.read(); if ( i&gt;3){ Serial.print(data[i], HEX); Serial.print(" "); } } } void loop() { } </code></pre>
<p>From the DS2502 datasheet:</p> <blockquote> <p><strong>Skip ROM [CCh]</strong></p> <p>This command can save time in a single-drop bus system by allowing the bus master to access the memory functions without providing the 64-bit ROM code. If more than one slave is present on the bus and a read command is issued following the Skip ROM command, data collision will occur on the bus as multiple slaves transmit simultaneously (open drain pulldowns will produce a wired-AND result).</p> <p><strong>READ MEMORY [F0h]</strong></p> <p>The Read Memory command is used to read data from the 1024-bit EPROM data field. The bus master follows the command byte with a 2-byte address (TA1=(T7:T0), TA2=(T15:T8)) that indicates a starting byte location within the data field. An 8-bit CRC of the command byte and address bytes is computed by the DS2502 and read back by the bus master to confirm that the correct command word and starting address were received. If the CRC read by the bus master is incorrect, a reset pulse must be issued and the entire sequence must be repeated. If the CRC received by the bus master is correct, the bus master issues read time slots and receives data from the DS2502 starting at the initial address and continuing until the end of the 1024-bit data field is reached or until a reset pulse is issued. If reading occurs through the end of memory space, the bus master may issue eight additional read time slots and the DS2502 will respond with a 8-bit CRC of all data bytes read from the initial starting byte through the last byte of memory. After the CRC is received by the bus master, any subsequent read time slots will appear as logical 1s until a reset pulse is issued. Any reads ended by a reset pulse prior to reaching the end of memory will not have the 8-bit CRC available.</p> </blockquote> <p>So you are telling it that you want to read the memory from whatever device is on the bus, not any one specific one (since you are not needing to provide the ROM ID to identify the exat item on the bus), starting from address ((0 &lt;&lt; 8) |10) = 10.</p> <p>From the DS2502-E48 datasheet you can see the layout of the memory:</p> <blockquote> <p>The data record starts with a length byte (0Ah) and the 4-byte UniqueWare Project ID 00001129h. The next 6 bytes contain the 48-bit node address which consists of an incrementing 24-bit extension identifier and the IEEE-assigned 24-bit company ID value 006035h. An inverted 16-bit CRC ends the data record. The remaining bytes of the 32-byte memory page remain unprogrammed. Neither the 24-bit extension identifier nor the 24-bit company ID are related to the 64-bit ROM registration number. The ROM registration number is used to provide a unique address to access the DS2502-E48 when multidropped on a 1-Wire bus.</p> </blockquote> <p>So translating that into something more pictorial:</p> <pre><code>// Length byte 0x00: 0x0A // UniqueWare PID 0x01: 0x00 0x02: 0x00 0x03: 0x11 0x04: 0x29 // Serialization ("extension") number 0x05: 0x?? 0x06: 0x?? 0x07: 0x?? // Company ID Value 0x08: 0x?? 0x09: 0x?? 0x0A: 0x?? // 16-bit CRC 0x0B: 0x?? 0x0C: 0x?? // All the rest is EEPROM data 0x0D - 0x7F: 0x?? </code></pre> <p>So by starting at address 10 (0x0A) you are reading the last byte of the company ID, the CRC, and then whatever else is in the memory after that.</p> <p>To read the entire MAC address (least significant byte first) you should be starting to read at address 5.</p>
17344
|wifi|
Particle-like wifi configuration
2015-10-30T20:20:31.430
<p>Can anybody tell me how the <a href="https://docs.particle.io/guide/getting-started/start/core/" rel="nofollow">Particle (Photon/Core)</a> WiFi <em>setup</em> works?</p> <p>I am looking to mimic this WiFi configuration format for my own device.</p> <p>The basic steps are as follows:</p> <ol> <li>Power device on; put in "listening mode" if not already active;</li> <li>Connect smartphone to the wireless network that you want to connect your device to;</li> <li>Open the Tinker/Spark/whatever-it's-called App on your smartphone; choose "Add New Device";</li> <li>Enter wireless password;</li> <li>Wait for device to be discovered by the App; device is now connected to WiFi.</li> </ol> <p>How is the information (SSID, password) transferred from the smartphone to the device?</p> <p>Thanks in advance.</p>
<p>The Particle Photon is a replacement for the Spark Core module. This module was exploiting the Texas Instrument CC3000 chip. It was this chip that handle the very simple and convenient Wi-Fi configuration of the Spark Core. Texas Instrument named this method : <a href="http://www.ti.com/ww/en/simplelink_embedded_wi-fi/tools_software.html" rel="nofollow">SimpleLink</a>.</p> <p>The Particle Photon is now using a different module than the Core : a Broadcom BCM43362 instead of the CC3000. It's seems to work in a similar manner even if I was not able to find any information on it.</p> <p>I've found on the George Howkins <a href="http://depletionregion.blogspot.fr/" rel="nofollow">Depletion Region blog</a> multiple articles that explain how the CC3000 SimpleLink works.</p> <ul> <li><a href="http://depletionregion.blogspot.fr/2013/10/cc3000-smart-config-transmitting-ssid.html" rel="nofollow">CC3000 Smart Config - transmitting SSID and keyphrase</a></li> <li><a href="http://depletionregion.blogspot.fr/2013/10/cc3000-advertises-presence-on-network.html" rel="nofollow">CC3000 advertises presence on network via DNS-SD</a></li> </ul> <p>All the posts : <a href="http://depletionregion.blogspot.fr/search?q=smart+config" rel="nofollow">http://depletionregion.blogspot.fr/search?q=smart+config</a></p>
17349
|arduino-uno|arduino-mega|wifi|communication|esp8266|
Connecting two arduinos using WiFi
2015-10-31T05:51:03.183
<p>I have two arduinos (An UNO R3 and a Mega 2560), and I need to communicate them via two ESP8266 modules to exchange some values.</p> <p>In one arduino I'll use a SW-420 vibrarion module, and I need to send a value wirelessly to the other board, which it'll have an LCD screen that will display a message when a value is recieved.</p> <p>How can I do that with that specific WiFi modules? Thanks in advance</p>
<p>Step 1: I would load NodeMCU on you ESP8266: <a href="https://github.com/nodemcu/nodemcu-firmware" rel="nofollow">https://github.com/nodemcu/nodemcu-firmware</a></p> <p>Step 2: Connect to your home router or make an ap on one of your ESP and connect them... use the api: <a href="https://github.com/nodemcu/nodemcu-firmware/wiki/nodemcu_api_en" rel="nofollow">https://github.com/nodemcu/nodemcu-firmware/wiki/nodemcu_api_en</a> over serial connection</p> <p>Step 3: write a TCP server:</p> <pre><code>srv=net.createServer(net.TCP) srv:listen(80,function(conn) conn:on("receive",function(conn,payload) print(payload) //This payload will be send to your arduino over soft serial conn:send("&lt;h1&gt; Hello, NodeMCU!!! &lt;/h1&gt;") end) conn:on("sent",function(conn) conn:close() end) end) </code></pre> <p>Step 4: write a TCP client:</p> <pre><code>suc = false; function sendData( host, pathData ) suc = false; print("GoSending!"); -- A simple http client conn=net.createConnection(net.TCP, 0) conn:on("receive", function(conn, payload) if(string.find(payload, "200 OK")~=nil) then suc = true; print("AllDone") else suc = false; end end) conn:on("connection", function(c) print("connected"); conn:send("GET /".. pathData .." HTTP/1.1\r\nHost: ".. host .."\r\n" .."Connection: keep-alive\r\nAccept: */*\r\n\r\n") end) conn:on("disconnection", function() if(suc==false) then print("ErrorSending") end end) conn:on("reconnection", function() print("reconnection") end ) conn:connect(80,host) end </code></pre> <p>Step 5: Connect your esp boards with software serial to the arduino</p> <p>Step 6: write (from board 1) to softserial to esp1: sendData( hostIP, yourData) </p> <p>Step: 7 Parse the Data on sofserial read on the second arduino</p> <p>Step 8: DONE!</p> <p><strong>EDIT:</strong> </p> <p>Ok more infos on step 6. If you got your script running on your esp, you can call functions by sending the function name with parameters over your serial connection. So, this is some example code for your ardoino if you got the script from above:</p> <pre><code>SoftwareSerial wifi(3, 2); // RX, TX //at some time in your programm //Build up your string that will be send over serial String i1 = "sendData(\"ipFromTheServer\", \"send.php?d="; String i2 = i1+dataToSend; String i3 = i2 +"\");"; wifi.println(i3); </code></pre> <p>This will call the sendData function on you esp. this will call the send.php on a Server... you can put a server up on an other esp and call it (dont have to be a php page)</p> <p>More infos on step 7. the script on top will always print all incoming data. So you just have to read serial data on wifi:</p> <pre><code>if (wifi.available()) Serial.write(wifi.read()); //this will print all inc data to your arduino console (serial) parse this data! </code></pre> <p>Info: I've build this on my own... dont know if this is best practice :)</p>
17351
|arduino-uno|robotics|
What is the best arduino board for a robotic arm?
2015-10-31T09:57:36.367
<p>In my university we need to buy arduino boards and kits to build a moving robotic arm, that moves up and down and clockwise in a specific degree (almost like humans's).</p> <p>So, what's the most <strong>suitable</strong> arduino board to build this arm? I suggested to use the basic UNO board, but we may need to use relays (for example) if the power source is 12volts. So there is should be a better one.</p> <p>My regards.</p>
<p>Best answer is Arduino Uno because it is enough for your application. </p> <p>But all Arduino are works on 5 volt or 3.3 volt.</p> <p>For operating 12 volt devices use transistors or MOSFETs.</p>
17375
|arduino-uno|serial|shields|xbee|wireless|
PC <-> Xbee <-> Another Xbee Communication
2015-10-31T18:41:25.200
<p>I have this application where I want to send commands from the PC to an Arduino, remotely, and receive an answer back.</p> <p>The hardware configuration I'm using to achieve that is the following:</p> <pre><code>PC &lt;--&gt; Arduino with an Xbee &lt;--&gt; Another Arduino with another Xbee </code></pre> <p>It's just half-duplex communication. Everything seems easy, but there is a problem.</p> <p>Each Arduino has an Xbee Shield with an Xbee module connected to it. Reading the documentation of the ArduinoXbeeShield, an excerpt caught my eye:</p> <p><em>"With the jumpers in the Xbee position (i.e. on the two pins towards theinterior of the board), the DOUT pin of the Xbee module is connected to the RX pin of the microcontroller; and DIN is connected to TX. Note that the RX and TX pins of the microcontroller are still connected to the TX and RX pins (respectively) of the FTDI chip - data sent from the microcontroller will be transmitted to the computer via USB as well as being sent wirelessly by the Xbee module. <strong>The microcontroller, however, will only be able to receive data from the Xbee module, not over USB from the computer</strong>.</em></p> <p><em>With the jumpers in the USB position (i.e. on the two pins nearest the edge of the board), the DOUT pin the Xbee module is connected to the RX pin of the FTDI chip, and DIN on the Xbee module is connected to the TX pin of the FTDI chip. This means that the Xbee module can communicate directly with the computer - <strong>however, this only works if the microcontroller has been removed from the Arduino board. If the microcontroller is left in the Arduino board, it will be able to talk to the computer normally via USB, but neither the computer nor the microcontroller will be able to talk to the Xbee module</strong>."</em></p> <p>That means I will not be able to build what I want with this configuration? I already tried, but didn't work.</p>
<p>Basically with your shield you have two options:</p> <ol> <li>Communicate between the MCU and the XBee at the cost of not being able to communicate between the PC and the MCU.</li> <li>Communicate between the PC and the XBee at the cost of having to remove the MCU from the board completely.</li> </ol> <p>Neither of which are particularly ideal. The first option is completely out since that rules out all PC communication. The second option turns the Arduino into just a USB->TTL Serial adapter - and a rather expensive one at that (you can get them on eBay for like $2).</p> <p>What you want is to re-wire the system using jumper wires (messy, I know) so that the TX and RX pins of the XBee connect to other pins on your Uno then use SoftwareSerial to communicate with the XBee. That will leave the Arduino's TX and RX pins free for communicating with the PC.</p> <p>Alternatively invest in a different Arduino that has more hardware UART interfaces, like a Mega2560.</p>
17385
|serial|arduino-due|linux|
Why does Arduino Due Native Port change serial ports after every reset? (Linux)
2015-11-01T01:45:24.173
<p>Previously I had my Due connected via Programming Port for weeks, and it never changed serial ports after pressing the reset button. Recently I switched to having it connected via the Native Port instead, and was surprised to see that it changes port numbers every time I press the reset button. </p> <p>For example if it was on ttyATM1 beforehand, after pressing reset it'll be on ttyATM2 instead. It changes numbers like this after every reset. Is this normal behavior?</p> <p>I have a python script sending serial data to the Due, and I have to change the port number in the python code every time the Due changes ports. </p>
<p>It happens because of Linux, not because of the Arduino. Since you unplug/reset the DUE while the port is still open, when it's back online, the old file name is still in use, so a new one is created. Just close the port before resetting the DUE and you will see that after the reset it will have the same one.</p> <p>You can easily reproduce the same issue with a serial to usb adapter (/dev/ttyUSBS0,1,2,etc) and screen or minicom.</p> <p>To make your program more robust, you should listen for kernel events and open the port accordingly.</p>
17406
|power|arduino-nano|
Ultrasonic sensor returns random values on external power supply
2015-11-01T20:31:33.477
<p>my Problem is, that I get random values from my ultra sonic sensor if my arduino is connected to any external power supply (vin port 30) on my arduino nano.</p> <p>If I power up from the laptop usb port, I get consistent values. </p> <p>I have tested 3 different power supplies between 7-17V and up to 2000mA. I have tested this on 2 different nano boards. Also tested with an extra 2000uF capacitor between vin and gnd</p> <p>pls help if you got an idea :)</p>
<p>So i tried to used a stable 5V input on the 5V input pin and got the same more or less random values (jumping all around... especially on targets more than 1m away) </p> <p>So I changed form newPing lib (<a href="http://forum.arduino.cc/index.php?topic=37712.0" rel="nofollow">http://forum.arduino.cc/index.php?topic=37712.0</a>) to Ultrasonic lib (<a href="http://forum.arduino.cc/index.php?topic=37712.0" rel="nofollow">http://forum.arduino.cc/index.php?topic=37712.0</a>).</p> <p>Now the values are correct on each power supply and even more accurate on high distance than with newPing on USB power supply.</p> <p>Don't know whats broken with the newPing v1.7 lib -.- but this works!</p>
17416
|arduino-uno|motor|battery|
I have two 6 volts DC motors connected to L298N motor Driver. Do I need to use 12 Volts battery?
2015-11-02T10:47:45.553
<p>I have <strong>two 6 volts DC motors</strong> connected to <strong>L298N motor Driver</strong>. Do I need to use 12 Volts battery?</p>
<p>No, you need to use a (roughly) 6V battery. They are 6V motors, so they need a 6V battery.</p> <p>However, you <em>do</em> need to sum the <em>currents</em> not the voltages. The battery must be able to provide <em>at least</em> the current required by <em>both</em> motors together.</p>
17428
|motor|temperature-sensor|
Arduino + TMP36 + DC Motor
2015-11-02T19:12:46.803
<p>I made this circuit: </p> <p><a href="https://i.stack.imgur.com/D1Oye.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/D1Oye.png" alt="enter image description here"></a></p> <p>The part with the DC motor is from this tutorial: <a href="https://learn.sparkfun.com/tutorials/sik-experiment-guide-for-arduino---v32/experiment-12-driving-a-motor" rel="nofollow noreferrer">https://learn.sparkfun.com/tutorials/sik-experiment-guide-for-arduino---v32/experiment-12-driving-a-motor</a> ( I only use another resistor, with 220 OHM)</p> <p>As you can see, I also have a TMP36 sensor attached. What I would like to do is this: When the temperature is 25 degrees or more, the motor should turn on. </p> <p>I have this code:</p> <pre><code>//TMP36 Pin Variables int sensorPin = 0; //the analog pin the TMP36's Vout (sense) pin is connected to //the resolution is 10 mV / degree centigrade with a //500 mV offset to allow for negative temperatures /* * setup() - this function runs once when you turn your Arduino on * We initialize the serial connection with the computer */ void setup() { Serial.begin(9600); //Start the serial connection with the computer //to view the result open the serial monitor } void loop() // run over and over again { //getting the voltage reading from the temperature sensor int reading = analogRead(sensorPin); // converting that reading to voltage, for 3.3v arduino use 3.3 float voltage = reading * 5.0; voltage /= 1024.0; // print out the voltage Serial.print(voltage); Serial.println(" volts"); // now print out the temperature float temperatureC = (voltage - 0.5) * 100 ; //converting from 10 mv per degree wit 500 mV offset //to degrees ((voltage - 500mV) times 100) Serial.print(temperatureC); Serial.println(" degrees C"); if(temperatureC &gt;= 25){ analogWrite(9, 250); } delay(1000); //waiting a second } </code></pre> <p>But I get this result:</p> <pre><code>0.74 volts 24.22 degrees C 0.74 volts 24.22 degrees C 0.74 volts 24.22 degrees C 0.74 volts 24.22 degrees C 0.74 volts 24.22 degrees C 0.74 volts 24.22 degrees C 0.75 volts 25.20 degrees C &lt;------ 0.87 volts 36.91 degrees C 0.66 volts 16.41 degrees C 0.78 volts 27.64 degrees C 0.77 volts 26.66 degrees C 0.84 volts 34.47 degrees C </code></pre> <p>The point where the sensor measures > 25 degrees, the motor turns on but the circuit gets "poluted" and the temp sensor starts to send all kinds of strange values.</p> <p>How do I solve this? Thanks in advance!</p> <hr /> <p>I got it to work in with the following: http:// i.stack.imgur.com/4GFPH.png</p>
<p>Motors tend to use more current than the arduino can supply, try hooking up the motor to a different power supply than the arduino 5V. What most likely is happening, is that when the motor turns on, it alters the value of the voltage, which the temperature sensor is using to tell the arduino what the temperature is. You need to have the temperature sensor hooked up to the arduino to have the reference at the right voltage, so the motor should be on a different power supply. That should fix things.</p>
17436
|sensors|c++|arduino-nano|
Using / calibrating pH sensor module
2015-11-02T21:43:29.853
<p>I've bought this sensor module board to link to an Arduino nano: <a href="http://www.ebay.com/itm/For-Arduino-Liquid-PH-Value-Detection-detect-Sensor-Module-Monitoring-Controller/321764233326" rel="nofollow">http://www.ebay.com/itm/For-Arduino-Liquid-PH-Value-Detection-detect-Sensor-Module-Monitoring-Controller/321764233326</a></p> <p>I assumed the two screws were for calibration (low point + slope), but it seems the operation is different and I can't figure out how. I've got two reference liquids for pH of 4.0 and 7.0. When I put the probe in either one, I get readings. Turning one of the two screws seems to offset the reading so for instance I had pH 4 = 900 and pH 7 = 1000 (0 - 1023 range). Turning one of two screws would lower the value a bit, but it never gets below 500 or so. </p> <p>So what I can do is measure two points (4.0 and 7.0) and their respective measurement values. That way I could calculate points in between, but as far as I know pH is not a linear scale, but logarithmic. If I get this wrong, the reading might seem right but only show 4.0 and 7.0 correct and not the rest of the values (I don't have 10.0 reference fluid at the moment). </p> <p>Now onto the second screw, that one at first seemed to do nothing. But then I noticed that it sets some kind of threshold value, turning a LED on the board on and off. That LED seems to be linked to the value being read, but it's further purpose? Calibration? No idea. </p> <p>Ok so best case someone has an equal module and wants to detail how it works. Otherwise maybe some of you have some bright ideas on what I could try in order to get this to work the way I want it to :) </p> <p><strong>Update 09-11-2015</strong> </p> <p>Got feedback from the seller. She sent me the following ZIP: <a href="http://1drv.ms/1MSk1DX" rel="nofollow">http://1drv.ms/1MSk1DX</a>. It contains some files in Chinese but one had sourcecode in it. Tried it on my Arduino but unfortunately the values still don't make much sense. Depending on how I turn the knob on the print, I get values between 9 and 17 for a liquid that's in real life 7.0. I didn't try but doubt that doing a -7 offset is sensible. </p> <p>The code itself is pretty straightforward, taking a 6-center average of ten consecutive measures. The interesting lines are these:</p> <pre><code> avgValue = 0; for (int i=2;i&lt;8;i++) // take the average value of 6 center sample avgValue+=buf[i]; float phValue = (float)avgValue*5.0/1024/6; // convert the analog into millivolt phValue=3.5*phValue+Offset; </code></pre> <p>Maybe someone can make sense of this, because I can't. I don't understand the 5.0 multiplication and the 3.5 after that one. Where do these come from? </p> <p>Anyway, when I dip the probe into the storage liquid, my normal meter plummets to pH 0.5 whilst the software is giving me 17 (which is a higher value than the one I got from reading my 7.0 liquid). So either my board is broken or this sample code is useless.</p> <p>Schematics can be found in the ZIP file by the way. </p> <p><strong>Update 11-11-2015</strong></p> <p>Did some more experimenting. First I found out that the readings from the module increased for more acidic liquid. So I reversed the value by using </p> <pre><code>buf[i]=1024 - analogRead(SensorPin); </code></pre> <p>Ok, now the values made more sense. Then I adjusted the pot to be in the middle of the available range. I dipped the probe in the 7.0 liquid, read the value and adjusted the offset. Then dipped in 4.0, adjusted the pot to match with 4.00, here are the results: </p> <pre><code>pH 7.0 reference --&gt; 6.27 set offset to: 0.73 pH 4.0 reference --&gt; 5.17 adjusted the pot so value read 4.0 pH 7.0 reference --&gt; 5.86 </code></pre> <p>So as I expected, adjusting the pot also messes up the 7.0 reference measurement. I then though it might be because of the slope of the pot (if there would be any), so I went to the lowest value first to have the least difference. Again the readings:</p> <pre><code>pH 7.0 reference --&gt; 8.70 set offset to: -1.70 pH 4.0 reference --&gt; 5.17 adjusted the pot so value read 4.0 pH 7.0 reference --&gt; 5.70 </code></pre> <p>The interesting thing here is that the 4.0 value reads 5.17 in both cases, even though the pot was in a different position. I cannot explain why though. </p> <p>To make sure the probe is fine I re-calibrated my normal pH meter, operates as usual. This one also has two pots, one for 7.0 calibration and one for 4.0 slope. Calibration is done by setting 7.0, then measuring 4.0 and ajusting the slope pot. Measure 7.0 again, change 7.0 pot, measure 4.0 again, etc. until the values match their liquids. Usually takes me about 3 - 4 loops to get it right. </p> <p><strong>Another update</strong></p> <p>Took the two containers of reference fluids and started mixing. This gave me measurements in the range of pH 4 - 7.5. Also measured the storage liquid which has a pH of 1.00. Results are in an Excel sheet: <a href="http://1drv.ms/1lkAO6e" rel="nofollow">http://1drv.ms/1lkAO6e</a>. Next question is how to convert this into a suitable formula?</p> <p><strong>Update 18-11-2015</strong> </p> <p>Working on @slash-dev's solution, here's what I did: </p> <p>I first turned the pot all the way down to the lowest value. The readings (for pH 7.0) are as follows: low = 540 and high = 1017. Code as follows:</p> <pre><code>int rawValue = analogRead(SensorPin); int buf[10]; //buffer for read analog for(int i=0;i&lt;10;i++) //Get 10 sample value from the sensor for smooth the value { buf[i] = rawValue; delay(10); } // sorting left out to reduce the sample length int avgValue=0; for(int i=2;i&lt;8;i++) // take the average value of 6 center samples avgValue += (buf[i] - CENTER); </code></pre> <p>In this stage I'm printing the raw value of course. </p> <p>The shorting of the BNC connector I don't exactly understand, should I short the inside (where the pin goes) or the outside of the connector? And short it to the GND? I used the reference solution instead.</p> <p>Now I added the formula to determine the voltage. For the low value that reads 0.10. I now put in the center value of 540 which brings the voltage reading to 0.0, seems good. </p> <p>Now for step 2 I placed the probe into the 4.0 reference solution. The voltage now reads 0.48, raw value 637. I start adjusting the pot to where the voltage reads 2.25, takes quit some adjusting. Raw now reads 1000.</p> <p>Now comes the part I don't exactly get. You say we can now calculate the pH/V, but with what variables? I mean, -3 / 2.25 will always result in -1.33 but shouldn't there be a variable here depending on how far I actually adjusted the pot? </p> <p>When I now put in the formula to calculate the pH as expected it reads 4.0 for the 4.0 reference solution. But it now screws up the 7.0 solution as we adjusted the pot but didn't compensate for it as far as I see? I also tried the adjusted pH formulas but I guess those are meant for the first code we had and not this adjusted one. </p> <p>So what am I missing between step 2 and 3 that messes up things here? Also, you state that the inverting by subtracting from 1024 is correct, but when I do that the voltage readings become minus. </p> <p>Another thing I wonder about; if the pot has to be a slope, shouldn't it be a different one than the one next to it (where a linear one makes more sense)? Cause it isn't, they both read "W103 / 143C". In the meantime, the vendor is kindly sending over a replacement one to ensure it's not a hardware defect somewhere. </p> <p><strong>Next update: :)</strong></p> <p>So I now reverted to my original code to try the adjusted pH calculations. I used the 7.0 reference solution to calibrate again and then measured the 4.0 solution. It reads 4.1! Ok, not completely spot on but not bad either. It's a small difference which might as well come from the probe, not the most expensive one.</p> <p>So I wonder whether we should still try to get the other approach working cause it sounds better (more scientific?) for some reason. Anyway, this is at least a whole lot better than nothing :) </p> <p><strong>USB power vs linked?</strong> Another strange thing seems to happen when I disconnect the Nano from the USB port of my laptop and instead power it via a Raspberry. I want to use I2C to send the value from the Nano to the RPi. This works, but as soon as I power the nano from the RPi (5V connected to vIn), the calculated pH value drops?</p>
<blockquote> <p><strong>USB power vs linked</strong></p> </blockquote> <p>Just to add my 2 cents on your latest update about the USB or 5V from the PI.</p> <p>You say you connect it to the VIN:</p> <blockquote> <p>as soon as I power the nano from the RPi (5V connected to vIn), the calculated pH value drops?</p> </blockquote> <p>If you look at the below image you see that Vin goes to a good old 7805, which needs a IN voltage > 7.5V, thus the output when its connected to the 5V of the PI is going to be very low and thus mess up readings.</p> <p><img src="https://i.stack.imgur.com/52yDH.png" alt="enter image description here"></p> <p>I recommend you connect your <strong><em>power from the PI to the arduino's VCC</em></strong> as this is a regulated 5v and doesn't need to be regulated again.</p>
17443
|button|teensy|millis|midi|debounce|
How to simulate delay() to debounce mechanical button using millis()?
2015-11-03T10:07:02.120
<p>Im trying to use the millis() function as a replacement for the delay() function in order to debounce a mechanical button. This is for an electric drum kit I am building. Im using a teensy Arduino to send MIDI signals from the drum pads to an external music program. The mechanical button needs to be responsible for cycling through five different states which change the MIDI signal sent from each pad, thus changing the sound, as well as lighting up one of five LEDs on my drum pad so I know which state i'm in. However I cant use delay() to debounce the button because that effects the efficiency of the drum pads, with some hits not being registered, latency etc.</p> <p>Im trying to debug the code by just getting the LEDs to light up correctly when I press the button. This was the original code I wrote with the delay() function. This worked perfectly to debounce the button, but messed with my drum pads:</p> <pre><code>int but = 12; int led0 = 7; int led1 = 8; int led2 = 9; int led3 = 10; int led4 = 11; int ledCase = 0; int butState = 0; int oldButState = 0; void setup() { pinMode(led0, OUTPUT); pinMode(led1, OUTPUT); pinMode(led2, OUTPUT); pinMode(led3, OUTPUT); pinMode(led4, OUTPUT); pinMode(but, INPUT_PULLUP); } void loop() { oldButState = digitalRead(but); delay(10); butState = digitalRead(but); if (butState != oldButState &amp;&amp; butState == LOW) { ledCase += 1; oldButState = butState; } if (ledCase &gt; 4) { ledCase = 0; } Serial.println(ledCase); switch (ledCase) { case 0: digitalWrite(led0, HIGH); digitalWrite(led1, LOW); digitalWrite(led2, LOW); digitalWrite(led3, LOW); digitalWrite(led4, LOW); break; case 1: digitalWrite(led0, LOW); digitalWrite(led1, HIGH); digitalWrite(led2, LOW); digitalWrite(led3, LOW); digitalWrite(led4, LOW); break; case 2: digitalWrite(led0, LOW); digitalWrite(led1, LOW); digitalWrite(led2, HIGH); digitalWrite(led3, LOW); digitalWrite(led4, LOW); break; case 3: digitalWrite(led0, LOW); digitalWrite(led1, LOW); digitalWrite(led2, LOW); digitalWrite(led3, HIGH); digitalWrite(led4, LOW); break; case 4: digitalWrite(led0, LOW); digitalWrite(led1, LOW); digitalWrite(led2, LOW); digitalWrite(led3, LOW); digitalWrite(led4, HIGH); break; } } </code></pre> <p>This is what I tried to use to replace the delay() function, but that hasn't worked. Note I added these lines in and removed the delay section:</p> <pre><code>unsigned long onTime; unsigned long delayTime; void setup() { delayTime = millis() + 10; } void loop() { oldButState = digitalRead(but); onTime = millis(); if (onTime &gt;= delayTime) { butState = digitalRead(but); delayTime = millis() + 10; } } </code></pre> <p>Any pointers as to how I can make the millis() function work to debounce this would be would be very much appreciated, thank you :)</p>
<p>Actually, Majenko's diagram assumes the interplay of the pullup resistor forces the line back to a HIGH position (as quickly as the internal transistors can overpower the drop from the switch). If the switch itself is mechanical with a pullup resistor (external or internal), then the only thing "bouncing" is the switch. If you use a digital switch, the rise is much sharper without significant bounce.</p> <p>A cheap and effective debouncing tactic is to add a capacitor in parallel with the switch. The cap will drop to GND quickly as the switch drains the charge stored in the cap. But the cap will take a while to recharge since its only source is through the resistor (during which time the mechanicals settle down). (This looks much better in a diagram, but I haven't figured out how to draw on here yet.) I wish I could recommend values, but it really depends on the mechanicals of the switch and the certainty of the debounce desired--make everything HUGE and you're guaranteed no bounce, use values in between and you go on probabilities. I usually start out with 0.1uF and vary it up or down until I get a balance between reliability and speed.</p> <p>The main advantage is, of course, you use absolutely no computing time to debounce any number of switches. </p> <p>Potential disadvantages:</p> <ul> <li><p>Added hardware cost for each switch, making this technique less desirable in production scenarios</p></li> <li><p>0/1 thresholds of input pins will vary across the manufacturing process, so one cap / input pin may have a different debounce time than another on an identical circuit. </p></li> <li><p>Software debouncing schemes can note that the switch is pushed on the first drop to GND, where this hardware-only tactic relies on the last actual contact with GND. As the switch ages, I've seen this delay exceed 50 mSec.</p></li> <li><p>Since the bounce is mechanical at its core, bounce worsens over the life of the mechanical part (in this case the switch). Typically, software can be fine-tuned easier than hardware. Often, however, swapping out a cap is easier than reflashing firmware.</p></li> </ul>
17446
|voltage-level|arduino-pro-micro|
Pro Micro Voltage regulator burned
2015-11-03T12:16:46.057
<p>I'm using Arduino Pro Micro (5v version) in one of my project for my car. The car's 12V +ve connected to RAW input of ProMicro and everything seems to work perfectly until I crank the ignition of my car. Here's what actually happened, my circuit works perfectly fine when car's ignition is in ON state. However, as soon as I started my car the voltage dropped from 12v to between 9-10volt and the LG33 (SMD voltage regulator) burned out. Now, I want a good solution as what should I do now? I have already LM2596 DC 3A Step-Down regulator. So should I use that to step-down 12v to 5v OR is there anything else I can do which might be a better solution?</p>
<p>What happened was the ignition caused massive spikes on the 12V power. You require an automotive grade regulator that can cope with spikes in excess of around 70V or more.</p> <p>Your best bet is probably a car USB charger adapter since they are cheap and easy to get hold of.</p>
17453
|usb|button|teensy|keyboard|debounce|
Arduino sending keystrokes via push-buttons. Proper bouncing and manually setting buttons?
2015-11-03T19:17:06.770
<p>I have a simple set of 8 push buttons wired to a Teensy 3.2 board (which uses Arduino via Teensyduino plugin). The 8 buttons are on pins 1-8 and their common ground line (one line soldered to each of them) is on the GND pin. I have code to get any one button working that works. It's currently set to make pressing the second button type "A."</p> <p>I'd like to make push buttons 1 through 8 type out A,B,C...etc respectively as you press them. I've been told of two problems with my setup, the first being that copying the code for every button is a bad way to go about it and second that it's subject to bouncing issues (creates a keystroke once every 5 presses or so.) I'd also like to set this up so in the future I can write a 3rd party app that configures the keys based on the user's preference.</p> <p>Adding those needs up I'm not sure where to go next. I'm beginner enough that I'm not sure how to properly incorporate the bounce class or if that's the right way to go given the needs.</p> <p>Is a matrix the way to go or is there an elegant way to manual set each button and compensate for bounce? I'd really appreciate a small example if anyone has done this. Thanks~ Current code follows:</p> <pre><code>#define CHECK_EVERY_MS 20 #define MIN_STABLE_VALS 5 unsigned long previousMillis; char stableVals; char buttonPressed; void setup() { // make pin 2 an input and turn on the // pullup resistor so it goes high unless // connected to ground: pinMode(2, INPUT_PULLUP); Keyboard.begin(); } void loop() { if ((millis() - previousMillis) &gt; CHECK_EVERY_MS) { previousMillis += CHECK_EVERY_MS; if (digitalRead(2) != buttonPressed) { stableVals++; if (stableVals &gt;= MIN_STABLE_VALS) { buttonPressed = !buttonPressed; stableVals = 0; if (buttonPressed) { //Send an ASCII 'A', Keyboard.write(65); } } } else stableVals = 0; } } </code></pre> <p><strong>-------</strong> <strong>Edit: WORKING CODE FOLLOWS</strong></p> <pre><code>/* jw - 3 Nov 2015 - Program for button debounce demo Ref: http://arduino.stackexchange.com/questions/17453/arduino-sending-keystrokes-via-push-buttons-proper-bouncing-and-manually-settin */ //-------------------------------------------------------- enum { sw0=3, sw1=4, sw2=5, sw3=6, sw4=7, sw5=8, sw6=9, sw7=10}; // Switchbutton lines enum { nSwitches=8, bounceMillis=42}; // # of switches; debounce delay struct ButtonStruct { unsigned long int bounceEnd; // Debouncing-flag and end-time // Switch number, press-action, release-action, and prev reading byte swiNum, swiActP, swiActR, swiPrev; }; struct ButtonStruct buttons[nSwitches] = { {0, sw0, 'A'}, {0, sw1, 'B'}, {0, sw2, 'C'}, {0, sw3, 'D'}, {0, sw4, 'E'}, {0, sw5, 'F'}, {0, sw6, 'G'}, {0, sw7, 'H'}}; //-------------------------------------------------------- void setup() { for (int i=0; i&lt;nSwitches; ++i) pinMode(buttons[i].swiNum, INPUT_PULLUP); Keyboard.begin(); } //-------------------------------------------------------- byte readSwitch (byte swiNum) { // Following inverts the pin reading (assumes pulldown = pressed) return 1 - digitalRead(swiNum); } //-------------------------------------------------------- void doAction(byte swin, char code, char action) { Keyboard.write(action); } //-------------------------------------------------------- void doButton(byte bn) { struct ButtonStruct *b = buttons + bn; if (b-&gt;bounceEnd) { // Was button changing? // It was changing, see if debounce time is done. if (b-&gt;bounceEnd &lt; millis()) { b-&gt;bounceEnd = 0; // Debounce time is done, so clear flag // See if the change was real, or a glitch if (readSwitch(b-&gt;swiNum) == b-&gt;swiPrev) { // Current reading is same as trigger reading, so do it if (b-&gt;swiPrev) { doAction(b-&gt;swiNum, 'P', b-&gt;swiActP); } else { doAction(b-&gt;swiNum, 'R', b-&gt;swiActR); } } } } else { // It wasn't changing; but see if it's changing now if (b-&gt;swiPrev != readSwitch(b-&gt;swiNum)) { b-&gt;swiPrev = readSwitch(b-&gt;swiNum); b-&gt;bounceEnd = millis()+bounceMillis; // Set the Debounce flag } } } //-------------------------------------------------------- long int seconds, prevSec=0; void loop() { for (int i=0; i&lt;nSwitches; ++i) doButton(i); } </code></pre>
<p>I'm not sure what you mean by “Is a matrix the way to go”, so will ignore that question.</p> <p>Shown below is a way of using an array of structs (one of C's ways of organizing a collection of items) to keep data for several buttons, such that it's straightforward to use one subroutine to process each button the same way, using a for-loop to call the routine for each button.</p> <p>Each element of the array <code>buttons</code> is a <code>ButtonStruct</code>, and each <code>ButtonStruct</code> contains five items: bounceEnd, swiNum, swiActP, swiActR, swiPrev, which respectively represent a debouncing-flag and end-time; a switch number [ie a pin number]; a code for action to take on a press; a code for action to take on a release; and previous state of button. (In many special cases, some of these items will be irrelevant and you can leave them out of the <code>ButtonStruct</code>.) The form <code>b-&gt;x</code> that is used in the <code>doButton()</code> routine says to access element <code>x</code> of the struct that <code>b</code> points to.</p> <p>At the start of each <code>loop()</code> pass, <code>doButton()</code> is called once for each button. It first tests if debouncing was underway for the button. If so, it sees if enough time has gone by to suppose button bounce is over. If so, it reads the button's state, and if different from previous state, does an action for whichever way the button changed. (If the button state is unchanged after a debounce delay, the program supposes there was a glitch.) If debouncing was not underway, the program checks if the button state is different from most recent pass. In that case, it sets up a debounce test for the button.</p> <p>The buttons are tested and debounced individually, as you can see in the sample output that is shown following the program. (This program was tested on an Uno, with four independent buttons used in the test. <em>Edit: Made corrections to handle 32-bit overflow, 2016.10.17</em>)</p> <pre><code>/* jw - 3 Nov 2015 - Program for button debounce demo Ref: http://arduino.stackexchange.com/questions/17453/arduino-sending-keystrokes-via-push-buttons-proper-bouncing-and-manually-settin */ //-------------------------------------------------------- enum { sw0=8, sw1=9, sw2=10, sw3=11}; // Switchbutton lines enum { nSwitches=4, bounceMillis=42}; // # of switches; debounce delay struct ButtonStruct { unsigned long int bounceGo; // Debouncing-flag and end-time // Switch number, press-action, release-action, and prev reading byte swiNum, swiActP, swiActR, swiPrev; }; struct ButtonStruct buttons[nSwitches] = { {0, sw0, 'A','a', 0}, {0, sw1, 'B','b', 0}, {0, sw2, 'C','c', 0}, {0, sw3, 'D','d', 0}}; //-------------------------------------------------------- void setup() { for (int i=0; i&lt;nSwitches; ++i) pinMode(buttons[i].swiNum, INPUT_PULLUP); Serial.begin(115200); Serial.println("Starting"); } //-------------------------------------------------------- byte readSwitch (byte swiNum) { // Following inverts the pin reading (assumes pulldown = pressed) return 1 - digitalRead(swiNum); } //-------------------------------------------------------- void doAction(byte swin, char code, char action) { Serial.print("Switch "); Serial.print(swin); Serial.print(code); Serial.print(' '); Serial.print(action); Serial.print(" at t="); Serial.print(millis()); Serial.println(); } //-------------------------------------------------------- void doButton(byte bn) { struct ButtonStruct *b = buttons + bn; if (b-&gt;bounceGo) { // Was button changing? // It was changing, see if debounce time is done. if (millis() - b-&gt;bounceGo &gt; bounceMillis) { b-&gt;bounceGo = 0; // Debounce time is done, so clear flag // See if the change was real, or a glitch if (readSwitch(b-&gt;swiNum) == b-&gt;swiPrev) { // Current reading is same as trigger reading, so do it if (b-&gt;swiPrev) { doAction(b-&gt;swiNum, 'P', b-&gt;swiActP); } else { doAction(b-&gt;swiNum, 'R', b-&gt;swiActR); } } } } else { // It wasn't changing; but see if it's changing now if (b-&gt;swiPrev != readSwitch(b-&gt;swiNum)) { b-&gt;swiPrev = readSwitch(b-&gt;swiNum); b-&gt;bounceGo = millis(); // Set the Debounce flag } } } //-------------------------------------------------------- long int seconds, prevSec=0; void loop() { for (int i=0; i&lt;nSwitches; ++i) doButton(i); } </code></pre> <p>In the sample output below, a P line indicates a button press, detected at given <code>millis()</code> time, and an R line indicates a button release. Observe, near the end, overlaps among separate button presses and releases.</p> <pre><code>Starting Switch 8P A at t=2170 Switch 8R a at t=2322 Switch 9P B at t=2789 Switch 9R b at t=2969 Switch 10P C at t=3395 Switch 10R c at t=3562 Switch 11P D at t=4087 Switch 11R d at t=4260 Switch 11P D at t=6518 Switch 10P C at t=6961 Switch 8P A at t=7070 Switch 10R c at t=7112 Switch 11R d at t=7427 Switch 8R a at t=7598 Switch 10P C at t=8502 Switch 9P B at t=8642 Switch 10R c at t=8961 Switch 9R b at t=9054 Switch 9P B at t=9954 Switch 11P D at t=10073 Switch 8P A at t=10164 Switch 8R a at t=10215 Switch 9R b at t=10315 Switch 11R d at t=10354 </code></pre>
17458
|power|current|
Circuit doesn't work when multimeter/current meter is attached
2015-11-04T01:07:01.997
<p>I'm working on a battery-powered data logger, using a bare Atmega 328. I'm using sleep between sensor readings, via the Narcoleptic library. Everything seems to work fine, until I connect my multimeter to check on the current.</p> <p>The multimeter uses manual range-setting (i.e., not autoranging). If I set the multimeter to the 0-20 mA range, I can see that my idle current is about 0.250 mA, but the upper value is off-scale. If I try to get a reading on the 0-200 mA range, the circuit misbehaves, never goes into sleep, and doesn't record any data. The current stays constant somewhere around 14-20mA.</p> <p>Do I need to do something special to accurately measure current in the range of 0.25-40+mA? Or do I need a different kind/quality of multimeter?</p> <p>My multimeter is a $15 digital unit from Circuit Test, model DMR-1100A. </p>
<p>Multimeters have something called a "burden voltage". See this PDF: <a href="http://www.eevblog.com/files/uCurrentArticle.pdf" rel="noreferrer">uCurrent - A professional precision current ... - EEVblog</a>.</p> <p>Also see Dave Jones' video: <a href="https://www.youtube.com/watch?v=i069j6S80OU" rel="noreferrer">µCurrent</a></p> <p>Meters measure current by dropping voltage over an internal resistor, and measuring the drop. By definition therefore, there is a voltage drop, which is the "burden voltage". </p> <blockquote> <p>the circuit misbehaves, never goes into sleep, and doesn't record any data</p> </blockquote> <p>If you put a voltmeter on the processor side of the ammeter you will probably find that the voltage going into your processor is somewhat less than you think. That would account for the misbehaving.</p> <p>One possible approach is to crank up the voltage from your power source, checking the voltmeter to see that it reaches the expected voltage on the <strong>processor</strong> side of the ammeter, however in a circuit which might turn on and off (ie. sleep) this voltage might jump around (depending on the current) so this should be done with caution (to not exceed the maximum processor voltage).</p> <hr> <blockquote> <p>Or do I need a different kind/quality of multimeter?</p> </blockquote> <p>A higher quality meter may well help - watch that video and look at the PDF to see what I am talking about. My meters (which cost more than $15) don't have this problem to the same extent.</p>
17465
|arduino-uno|pid|
Regulation of the temperature using PID
2015-11-04T12:55:50.273
<p>I'm making a control system for the heating of a plate using a PID control.</p> <p>the goal is to regulate the temperature of the plate by changing the power dissipated by the resistance. By using a sensor I read the temperature of the plate and is then used as the input in the PID control. I programmed also a signal wave square for the PWM. </p> <p>but the thing I don't understand is what I'm exactly supposed to do with the output signal I receive. and I cannot connect between the PWM and the PID. </p> <p>Code of the square signal:</p> <pre><code>void setup() { pinMode(9, OUTPUT); } void loop() { // phase haute digitalWrite(9,HIGH); delay(30); // phase basse digitalWrite(9,LOW); delay(70); //ton+toff = 0.1; // ton = 0.1*Output; } </code></pre> <p>Code of PID and the sensor</p> <pre><code>/******************************************************** * PID Basic Example * Reading analog input 0 to control analog PWM output 3 ********************************************************/ #include &lt;PID_v1.h&gt; int val; //Define Variables we'll be connecting to double Setpoint, Input, Output; //Specify the links and initial tuning parameters PID myPID(&amp;Input, &amp;Output, &amp;Setpoint,2,5,1, DIRECT); void setup() { Serial.begin(9600); //initialize the variables we're linked to Input = analogRead(1); Setpoint = 37; //temperature a reguler //turn the PID on myPID.SetMode(AUTOMATIC); } void loop() { val = analogRead(1); float mv = ( val/1024.0)*5000; float Input = mv/10; myPID.Compute(); analogWrite(3,Output); Serial.print("input temperature is :"); Serial.println(Input); delay (1000); // delay(1000); Serial.print("output is :"); Serial.println(Output); delay(1000); } </code></pre> <p>Thank you in advance</p>
<p>A PID only has one input and one output. In your case, the input will be the temperature. The use of the arduino would be to process the raw data of the temperature sensor and relay the temperature to the PID. Depending on the make and model of the PID, there could be certain transfer protocols you must adhere to. There are most likely open source libraries that will take care of transferring the data properly. </p> <p>Your PID is the piece of hardware that will "decide" when it is appropriate to turn the heater on and off, therefore it shall be responsible for driving the heater. That is what the output of the PID is responsible for. </p> <p>Lastly, your PID has a set point. In your case, the set point would be the desired max temperature of the plate. This set point is set and altered manually through user input. </p> <p>On a side note, if this is a personal project or a non deliverable, I'd recommend not using a PID. Try processing and analyzing all of the data exclusively on the Arduino, as it would be a challenging and rewarding task. </p>
17466
|ethernet|avr|spi|port-mapping|
Arduino W5100 AVR
2015-11-04T15:22:52.743
<p>I'm trying to use a W5100 Arduino Ethernet Shield on a ATMega2560 using avr code.</p> <p>There exists a library written in C, which should work <a href="http://www.seanet.com/~karllunt/w5100_webserv.zip" rel="nofollow">http://www.seanet.com/~karllunt/w5100_webserv.zip</a> from <a href="http://www.seanet.com/~karllunt/w5100_library.html" rel="nofollow">http://www.seanet.com/~karllunt/w5100_library.html</a></p> <p>The w5100_webserv.c should be a working example for an ATmega644p. He mentions that the four callback functions should be modified, namely my_select(), my_deselect(), my_xchg() and my_reset()</p> <p>The w5100_webserv.c also contains the following definitions for SPI_PORT/DDR CS_PORT/DDR/BIT and RESET_PORT/DDR/SPI:</p> <pre><code>/* * Define the SPI port, used to exchange data with a W5100 chip. */ #define SPI_PORT PORTB /* target-specific port containing the SPI lines */ #define SPI_DDR DDRB /* target-specific DDR for the SPI port lines */ #define CS_DDR DDRD /* target-specific DDR for chip-select */ #define CS_PORT PORTD /* target-specific port used as chip-select */ #define CS_BIT 2 /* target-specific port line used as chip-select */ #define RESET_DDR DDRD /* target-specific DDR for reset */ #define RESET_PORT PORTD /* target-specific port used for reset */ #define RESET_BIT 3 /* target-specific port line used as reset */ </code></pre> <p>I've changed it to the following according to what i think the ATmega2560's datasheet specifies</p> <pre><code>/* * Define the SPI port, used to exchange data with a W5100 chip. */ #define SPI_PORT PORTB /* target-specific port containing the SPI lines */ #define SPI_DDR DDRB /* target-specific DDR for the SPI port lines */ #define CS_DDR DDRB /* target-specific DDR for chip-select */ #define CS_PORT PORTB /* target-specific port used as chip-select */ #define CS_BIT 10 /* target-specific port line used as chip-select */ #define RESET_DDR DDRB /* target-specific DDR for reset */ #define RESET_PORT PORTB /* target-specific port used for reset */ #define RESET_BIT 20 /* target-specific port line used as reset */ </code></pre> <p>Furthermore, in the main(), there are also specific code for the AT644p:</p> <pre><code>/* * Initialize the ATmega644p SPI subsystem */ CS_PORT |= (1&lt;&lt;CS_BIT); // pull CS pin high CS_DDR |= (1&lt;&lt;CS_BIT); // now make it an output SPI_PORT = SPI_PORT | (1&lt;&lt;PORTB4); // make sure SS is high SPI_DDR = (1&lt;&lt;PORTB4)|(1&lt;&lt;PORTB5)|(1&lt;&lt;PORTB7); // set MOSI, SCK and SS as output, others as input SPCR = (1&lt;&lt;SPE)|(1&lt;&lt;MSTR); // enable SPI, master mode 0 SPSR |= (1&lt;&lt;SPI2X); // set the clock rate fck/2 </code></pre> <p>I've changed it to the following according to what i think the ATmega2560's datasheet specifies</p> <pre><code>/* * Initialize the ATmega2560 SPI subsystem */ CS_PORT |= CS_BIT; // pull CS pin high CS_DDR |= CS_BIT; // now make it an output SPI_PORT = SPI_PORT | (1&lt;&lt;PORTB0); // make sure SS is high SPI_DDR = (1&lt;&lt;PORTB0)|(1&lt;&lt;PORTB2)|(1&lt;&lt;PORTB1); // set MOSI, SCK and SS as output, others as input SPCR = (1&lt;&lt;SPE)|(1&lt;&lt;MSTR); // enable SPI, master mode 0 SPSR |= (1&lt;&lt;SPI2X); // set the clock rate fck/2 </code></pre> <p>Lastly i've changed the my_reset() function: void my_reset(void) { RESET_PORT |= RESET_BIT; // pull reset line high RESET_DDR |= RESET_BIT; // now make it an output RESET_PORT &amp;=~RESET_BIT; // pull the line low _delay_ms(5); // let the device reset RESET_PORT |= RESET_BIT; // done with reset, pull the line high _delay_ms(10); // let the chip wake up }</p> <p>I am not sure whether my changes are 100 % correct and i don't know what changes needs to be done to my_select() my_deselect and my_xchg. I hope someone can suggest som corrections.</p> <p>Thanks in advance.</p>
<p>I've managed to specify the correct ports and bits in order to make the library function on the Arduino ATmega2560 using their Ethernet Shield.</p> <p>The SPI port definitions has to be changed to the following:</p> <pre><code>#define SPI_PORT PORTB /* target-specific port containing the SPI lines */ #define SPI_DDR DDRB /* target-specific DDR for the SPI port lines */ #define CS_DDR DDRB /* target-specific DDR for chip-select */ #define CS_PORT PORTB /* target-specific port used as chip-select */ #define CS_BIT 4 /* target-specific port line used as chip-select */ #define RESET_DDR DDRB /* target-specific DDR for reset */ #define RESET_PORT PORTB /* target-specific port used for reset */ #define RESET_BIT 8 /* target-specific port line used as reset */ </code></pre> <p>The section about the AT644p in the main() function has to be changed to the following:</p> <pre><code>/* * Initialize the ATmega2560 SPI subsystem */ // Initial SPI Peripheral SPI_DDR = (1&lt;&lt;PORTB2)|(1&lt;&lt;PORTB1)|(1&lt;&lt;PORTB0); // CS pin is not active SPI_PORT |= (1&lt;&lt;CS_BIT); // Enable SPI, Master Mode 0, set the clock rate fck/2 SPCR = (1&lt;&lt;SPE)|(1&lt;&lt;MSTR); SPSR |= (1&lt;&lt;SPI2X); //Disable the SD card DDRB |= (1&lt;&lt;CS_BIT); </code></pre>
17467
|arduino-uno|
graph of a function Arduino
2015-11-04T15:43:36.977
<p>I am making a temperature circuit with arduino. is there any way to plot the value of the temperature in a graph using arduino? thank you very much in advance </p>
<p>Yes you can use the <a href="https://blog.arduino.cc/2015/11/03/arduino-ide-1-6-6-released-and-available-for-download/" rel="nofollow">Plot</a> menu command in the new Arduino 1.6.6 or you can use the <a href="http://www.visualmicro.com/post/2015/08/16/Arduino-Breakpoint-Command-Syntax-Plotting-Values-Example.aspx" rel="nofollow">Visual Micro debugger</a> to create graphs in Visual Studio</p>
17471
|core-libraries|build|
Alternative to patching core library source and header files
2015-11-04T17:57:15.757
<p>I am following a DIY guide that requires me to patch two arduino core library files: <code>HID.cpp</code> and <code>USBAPI.h</code>. This is not really practical for many reasons. I am not a native C programmer, but I am sure there are better ways to achieve the same without messing directly with system files. How can I override system library files without modifying the originals?</p>
<p>Unfortunately there <em>really</em> isn't any way of doing that other than modifying those files. The good news is that it is perfectly viable to make the modifications under a different "core" and then <a href="https://code.google.com/p/arduino/wiki/Platforms1" rel="nofollow">amend boards.txt</a> with the core containing the modifications.</p>
17477
|arduino-uno|timers|rtc|
Creating a timer using a Real Time Clock with start and stop times
2015-11-04T22:43:08.140
<p>I have an Arduino Uno with a motor shield, as well as a DS1307 RTC that I am using to control 2 pumps. </p> <p>Ideally I would like to set a start time (startHour + startMinute) and end time (endHour + endMinute) for each pump.</p> <p>I have had luck using <code>if</code> statements to control my timer like below (adapted from Iain Foulds):</p> <pre><code>byte startHour=8 byte startMinute=15 byte endHour= 14 byte endMinute= 20 byte startHour2=22 byte startMinute2=30 byte endHour2= 2 byte endMinute2= 45 void loop() { byte checkStartTime1() { DateTime now = RTC.now(); // Read in what our current datestamp is from RTC if (now.hour() == startHour &amp;&amp; now.minute() == startMinute) { validStart1 = 1; } else { validStart1 = 0; } return validStart1; // Return the status for powering up } } </code></pre> <p>But my concern is that this only checks for equivalency at the moment, and if I lost power when my start time came up my pump would not come on. So I was hoping to set up an <code>if</code> statement that can deal with ">=" as opposed to just "==".</p> <p>Which I can use if I only deal with the hour section:</p> <pre><code>if (now.hour() &gt;= startHour &amp;&amp; &lt;= endHour) </code></pre> <p>But things get complicated when I try to add in minutes to the control structure. I end up with a series of nested for loops that do not work.</p> <p>I'm hoping someone can help me write an <code>if</code> statement (or <code>switch case</code>) that can accommodate hours and minutes. So that any time between 8:15-14:20</p> <pre><code>validStart1=1 </code></pre> <p>and anytime other time </p> <pre><code>validStart1=0 </code></pre> <p>And please note the addition of the second set for this timer (StartHour2)- which I threw as my second pump will need to deal with the switch over past midnight.</p>
<p>A simple and effecient way is to use relative days and make use of the fact that the days, hours, minutes, and seconds are byte-sized data types that can fit into a single 32-bit data type.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">byte 3</th> <th style="text-align: center;">byte 2</th> <th style="text-align: center;">byte 1</th> <th style="text-align: center;">byte 0</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">Day</td> <td style="text-align: center;">Hour</td> <td style="text-align: center;">Minute</td> <td style="text-align: center;">Second</td> </tr> </tbody> </table> </div> <p>This can be achieved with the following function:</p> <pre class="lang-cpp prettyprint-override"><code>constexpr uint32_t MakeTimestamp(const byte day, const byte hour, const byte minute, const byte second) { // Pack the 4 individual bytes into a single 4-byte data type in order of precedence. return uint32_t(day) &lt;&lt; 24 | uint32_t(hour) &lt;&lt; 16 | uint32_t(minute) &lt;&lt; 8 | uint32_t(second); } </code></pre> <p>This 32-bit timestamp can be easily compared with other ones to test whether a timestamp is within a timespan:</p> <pre class="lang-cpp prettyprint-override"><code>bool WithinTimespan(const uint32_t&amp; timestamp, const uint32_t&amp; begin, const uint32_t&amp; end) { if (end &lt; begin) { // Crossing midnight. return timestamp &gt;= begin || timestamp &lt;= end; } // Single day. return timestamp &gt;= begin &amp;&amp; timestamp &lt;= end; } </code></pre> <p>By using relative days to declare the motor start and stop times, the comparison takes care of the rollover to tomorrow:</p> <pre class="lang-cpp prettyprint-override"><code>const byte motor1_start_hour = 8; const byte motor1_start_minute = 15; const byte motor1_stop_hour = 14; const byte motor1_stop_minute = 20; const byte motor2_start_hour = 22; const byte motor2_start_minute = 30; const byte motor2_stop_hour = 2; const byte motor2_stop_minute = 45; const uint32_t motor1_start_time = MakeTimestamp(0, motor1_start_hour, motor1_start_minute, 0); const uint32_t motor1_stop_time = MakeTimestamp(0, motor1_stop_hour, motor1_stop_minute, 0); const uint32_t motor2_start_time = MakeTimestamp(0, motor2_start_hour, motor2_start_minute, 0); const uint32_t motor2_stop_time = MakeTimestamp(0, motor2_stop_hour, motor2_stop_minute, 0); </code></pre> <p>Then the <code>loop()</code> is simply something like this:</p> <pre class="lang-cpp prettyprint-override"><code>void loop() { const DateTime now = rtc.now(); const uint32_t timestamp = MakeTimestamp(0, now.hour(), now.minute(), now.second()); bool motor1_on = WithinTimespan(timestamp, motor1_start_time, motor1_stop_time); bool motor2_on = WithinTimespan(timestamp, motor2_start_time, motor2_stop_time); UpdateMotor1(motor1_on); UpdateMotor2(motor2_on); } </code></pre>
17479
|accelerometer|
Can anyone tell me about the onboard accelerometer of LightBlue Bean?
2015-11-05T00:53:02.780
<p>I would like to know the specs of the accelerometer used on a LightBlue Bean before buying one, but I couldn't find any info online. Anybody has an idea?</p>
<blockquote> <p>I would like to know the specs of the accelerometer used on a LightBlue Bean before buying one, but I couldn't find any info online. Anybody has an idea?</p> </blockquote> <p>Start by checking the Adafruit <a href="https://www.adafruit.com/products/2732" rel="nofollow">LightBlue Bean</a> product description. There you can find a link to the <a href="https://www.adafruit.com/images/product-files/2732/Bean_revE_board_export.pdf" rel="nofollow">schematics and board layout</a>. On page two there is accelerometer, a BMA250 just as @Jason links to. </p> <p>That took "30 seconds" web search plus writing this answer :)</p> <p>Cheers!</p>