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
4511
|arduino-uno|serial|c++|
How to use output from Arduino in C++ code?
2014-10-08T10:43:31.877
<p>I am a complete novice in Arduino and moderately experienced with the language C++. What if I want to use the output from the serial monitor in C++ code in real time?</p> <p>Also how can I write to the serial monitor. Which libraries are available for this? Also please give me links to sites where I can learn more about this topic. I am using <a href="http://arduino.cc/en/Main/ArduinoBoardUno" rel="nofollow">Arduino Uno</a>.</p>
<pre><code>#include &lt;windows.h&gt; #include &lt;string&gt; #include &lt;stdio.h&gt; #define ARDUINO_WAIT_TIME 2000 using namespace std; string portNumber; HANDLE hSerial; bool connected; COMSTAT status; bool connectPrinter(char *portName){ //Connects to the port. hSerial = CreateFileA(portName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(hSerial==INVALID_HANDLE_VALUE) { if(GetLastError()==ERROR_FILE_NOT_FOUND){ printf("ERROR: Handle was not attached. Reason: %s not available.\n", portName); return false; } else { //If port is in use by another program or did not closed previous process. printf("ERROR!!! \n"); CloseHandle(hSerial); return false; } } else { DCB dcbSerialParams = {0}; if (!GetCommState(hSerial, &amp;dcbSerialParams)) { printf("failed to get current serial parameters!"); return false; } else { // Set Serial Port specifications. dcbSerialParams.BaudRate=CBR_115200; dcbSerialParams.ByteSize=8; dcbSerialParams.StopBits=ONESTOPBIT; dcbSerialParams.Parity=NOPARITY; if(!SetCommState(hSerial, &amp;dcbSerialParams)) { printf("ALERT: Could not set Serial Port parameters"); return false; } else { connected = true; printf("Connection Successful for :%s !!! \n" ,portName); //Wait 2s as the arduino board will be reseting return true; Sleep(ARDUINO_WAIT_TIME); } } } } int readData(char *buffer,unsigned int nbChar){ DWORD bytesRead; DWORD dwCommModemStatus; //Set the type of data to be caught.(RXCHAR -&gt; Data available on RX pin.) SetCommMask (hSerial, EV_RXCHAR ); while (hSerial != INVALID_HANDLE_VALUE) { // Wait for an event to occur for the port. WaitCommEvent (hSerial, &amp;dwCommModemStatus, 0); if (dwCommModemStatus &amp; EV_RXCHAR ) { //unsigned int toRead; //ClearCommError(this-&gt;hSerial, &amp;this-&gt;errors, &amp;this-&gt;status); do { // Read the data from the serial port. ReadFile (hSerial, buffer, 1, &amp;bytesRead, 0); // Display the data read. printf ("%s" ,buffer); } while (bytesRead &gt; 0); } } //} //If nothing has been read, or that an error was detected return -1 return -1; } int main() { char* buffer = new char[32768]; int nbChar= 32768; string str="COMx"; // Use your port number to connect char * writable = new char[str.size() + 1]; std::copy(str.begin(), str.end(), writable); writable[str.size()] = '\0'; connectPrinter(writable); delete []writable; readData(buffer,nbChar); return 0; } </code></pre> <p>try this one, it should work. Comment below if it does not work. You might reset Arduino to read data in method <code>void setup()</code> in Arduino code. I recommend you to use C#, Java or Python for efficiency.</p>
4520
|attiny|avrdude|
Extract .hex from ATtiny45 using Arduino
2014-10-09T07:39:11.900
<p>As it is possible to program a ATtiny45 using Arduino as ISP Programmer, is there a way to backup an ATtiny45 program to a .hex file using Arduino?</p>
<p>Assuming the lock bits on the device haven't been set, sure. Simply prepare the Arduino for ArduinoISP, hook up the ATtiny45, and perform a read using AVRDUDE instead of a write (<code>-U flash:r:foo.hex:i</code>).</p>
4522
|bluetooth|accelerometer|gyroscope|
Using IMU for a small Arduino and bluetooth support
2014-10-09T09:29:54.357
<p>I'm gonna start a project with an IMU with a bluetooth support inside a small board (mini or lillypad) and send datas to the mobile phone. But I'm quite new to those kind of technologies.</p> <p>I'm going to choose a module for handling both operate voltage restriction and memory capacity for both library (IMU and bluetooth).</p> <p>Any advice obj which arduino / IMU breakout / bluetooth module / battery to use? Or some similar projects?</p>
<p>If you're new to Arduino I'd suggest avoiding the Mini and the BULLSH-fun that external programmers bring. Something like the Pro Micro is much easier, almost as small, and less likely to bite.</p> <p>Often the best way to pick hardware is to look for a tutorial (like <a href="http://bildr.org/2012/03/stable-orientation-digital-imu-6dof-arduino/" rel="nofollow">This</a> one) before deciding what to buy. While I personally haven't used IMUs it looks like the "6 Degrees of Freedom IMU Digital Combo Board - ITG3200/ADXL345" from SparkFun would be (relatively) easy to use.</p> <p>I've used the RN-41/2 Bluetooth modems (the same as are found in BlueSMiRF modules) and usually gotten on OK with them. There are plenty of tutorials available with a bit of Googleing.</p> <p><a href="http://www.adafruit.com/categories/138" rel="nofollow">Adafruit</a> do a good line of Lipo batteries and chargers. They also have wireless charging modules if you're looking for extra brag-factor.</p> <p>Hope this helps.</p>
4528
|uploading|firmware|
How do send sketch updates to devices without the editor?
2014-10-09T14:02:57.657
<p>I'd like to update the sketch of a device that a friend out of state is testing. I could have them install the full editor and send the source code but I'd rather not require them to do something so technical.</p> <p>Is there a way to compile the firmware binary and push that out to a device over the COM port more directly?</p>
<p>In general, yes.</p> <p>The compile routine creates a .hex file in a temporary directory that contains the flash image for the device. One can use AVRDUDE to upload this .hex file to the Arduino from the command line. It is simply a matter of getting the command arguments correct in order to tell it where and how to upload the image. Enabling verbose output in the IDE will tell you both exactly where the .hex file is located and what arguments are required for the board selected.</p>
4531
|i2c|
How to wait for next n bytes in I2C exchange?
2014-10-09T15:32:15.680
<p>I'm trying to get data from a sensor, but don't see how I can get data back. I'm looking at the data on the I2C bus with a logic analyzer, and I'm sending what I expect, but I seem to cut off the slave before he can respond. My understanding from the <a href="http://www.consensic.com/DataSheet/DAT-0007,%20rev0.1%20CPS121%20Data%20Sheet.pdf" rel="nofollow">datasheet</a> is that I need to send this command to wake it up and request a measurement:</p> <p><code>0xD8 0x30 0x0A</code></p> <p>and then I need to send this command to get the data:</p> <p><code>0xD8 0x06 0xD9</code></p> <pre><code>#define HEARTBEAT_PIN (13) #define 7BIT_ADDR (0x6C) #define ADDR_WRITE (0xD8) #define ADDR_READ (0xD9) #define MAX_NUM_RX_BYTES (8) #define MAX_NUM_TX_BYTES (8) static uint8_t tx_buffer[MAX_NUM_TX_BYTES]; static uint8_t rx_buffer[MAX_NUM_RX_BYTES]; static uint8_t new_rx_data; void setup(void) { // Clear any module memory memset(tx_buffer, 0, MAX_NUM_TX_BYTES); memset(rx_buffer, 0, MAX_NUM_RX_BYTES); new_rx_data = false; Wire.begin(); } void loop(void) { RequestMeasurement(); delay(10); GetData(); delay(500); } void RequestMeasurement(void) { // MR: 0xD8 0x30 0x0A // Internal (to IC) register address? tx_buffer[0] = 0x30; // Request-measurement command tx_buffer[1] = 0x0A; Wire.beginTransmission(7BIT_ADDR); Wire.write(tx_buffer, 2); Wire.endTransmission(true); } void GetData(void) { // GD: 0xD8 0x06 0xD9 0x?? 0x?? 0x?? 0x?? 0x?? (0x?? =&gt; slave data) // Slave address + 'write' indication bit // Internal (to IC) register address? tx_buffer[0] = 0x06; // Slave address + 'read' indication bit tx_buffer[1] = ADDR_READ; Wire.beginTransmission(7BIT_ADDR); Wire.write(tx_buffer, 2); Wire.endTransmission(true); // HOW DO I LEAVE THE BUS OPEN LONG ENOUGH // FOR THE SLAVE DEVICE TO RESPOND WITH THE DATA? //Wire.requestFrom(7BIT_ADDR, 3, true); } </code></pre>
<p>Ensure pullups (see datasheet for min acceptable resistance) are on I2C lines.</p> <p>What I didn't understand at first was where the Wire library would bit shift and add read/write indication bits. And those start/stop booleans. After some testing and a closer read of the docs, I got this to work:</p> <pre><code>#include "Wire.h" #define BAR_7BIT_ADDR (0x6C) #define MAX_NUM_RX_BYTES (5) #define MAX_NUM_TX_BYTES (3) #define FIRST_TEMP_BYTE_INDEX (3) uint8_t new_rx_data; uint8_t tx_buffer[MAX_NUM_TX_BYTES]; uint8_t rx_buffer[MAX_NUM_RX_BYTES]; void setup(void) { Serial.begin(57600); Wire.begin(); } void loop(void) { // If new data is available if (new_rx_data) { new_rx_data = false; // Process the data in the background PrintRxData(); } BAR_RequestMeasurement(); BAR_GetData(); // This is a bit of a hack to get this function to execute. // After attempting to register this function as a callback with // the Wire.onReceive() method the function wouldn't execute. BAR_OnDataReceived(0); // Wait a tit, then do it again delay(500); } void RequestMeasurement(void) { // MR: 0xD8 0x30 0x0A // Internal (to IC) register address tx_buffer[0] = 0x30; // Request-measurement command tx_buffer[1] = 0x0A; Wire.beginTransmission(BAR_7BIT_ADDR); Wire.write(tx_buffer, 2); Wire.endTransmission(true); } void GetData(void) { // GD: 0xD8 0x06 0xD9 response from slave // Internal (to IC) register address tx_buffer[0] = 0x06; Wire.beginTransmission(BAR_7BIT_ADDR); Wire.write(tx_buffer, 1); Wire.endTransmission(false); Wire.requestFrom(BAR_7BIT_ADDR, 5, true); } void OnDataReceived(int num_bytes) { uint8_t i = 0; while (Wire.available() &amp;&amp; i &lt; MAX_NUM_RX_BYTES) { rx_buffer[i++] = Wire.read(); } // Indicate to the background that there is new rx data new_rx_data = true; } void PrintRxData(void) { Serial.print("Pressure [kPa]: "); Serial.print(ToKpa(rx_buffer)); Serial.print("\r\n"); Serial.print("Temperature [C]: "); Serial.print(ToCelsius(&amp;rx_buffer[FIRST_TEMP_BYTE_INDEX])); Serial.print("\r\n"); } // Returns the pressure in kPa given raw binary data float ToKpa(uint8_t* raw_data) { // example: raw_data[3] = {0x63, 0x6C, 0xBB}; =&gt; 101.81kPa // return ((float)((((uint32_t)raw_data[0]) * 65536) | // (((uint32_t)raw_data[1]) * 256) | // (((uint32_t)raw_data[2]) * 1))) / 64.0 / 1000.0; return ((float)(( (((uint32_t)raw_data[0]) &lt;&lt; 16) | (((uint32_t)raw_data[1]) &lt;&lt; 8) | (((uint32_t)raw_data[2]) &lt;&lt; 0) ) &gt;&gt; 6)) / 1000.0; } // Returns the temperature in Celsius given raw binary data float ToCelsius(uint8_t* raw_data) { // example: raw_data[2] = {0x18, 0xE6}; =&gt; 24.90C // return ((float)(((uint32_t)raw_data[0]) * 256) + (((uint32_t)raw_data[1]) * 1)) / 256.0; return ((float)( (((uint32_t)raw_data[0]) &lt;&lt; 8) | (((uint32_t)raw_data[1]) &lt;&lt; 0) )) / 256.0; } </code></pre>
4540
|arduino-due|compile|
Simple compiler design help: Variable length arrays in Arduino?
2014-10-10T16:29:49.010
<p>I'm trying to write a simple compiler in the Arduino language that I am making up for my lab. The compiler will have to be able to turn a string like this:</p> <pre><code>"do command_one 3 times" </code></pre> <p>into a data structure that represents this:</p> <pre><code>&lt;command_one&gt;, &lt;command_one&gt;, &lt;command_one&gt; </code></pre> <p>it should also be able to turn something more complicated like this:</p> <pre><code>"do do c_one do c_two 2 times 2 times c_thr 2 times" </code></pre> <p>into a data structure that represents this:</p> <pre><code>&lt;c_one&gt; &lt;c_two&gt; &lt;c_two&gt; &lt;c_one&gt; &lt;c_two&gt; &lt;c_two&gt; &lt;c_thr&gt; &lt;c_one&gt; &lt;c_two&gt; &lt;c_two&gt; &lt;c_one&gt; &lt;c_two&gt; &lt;c_two&gt; &lt;c_thr&gt; </code></pre> <p>Another function will then read the commands out one by one.</p> <p>These examples show all of the functionality that I would want from the compiler. </p> <p>I'm having design issues for the compiler that I want to create. Initially, I just wanted to do some string manipulation and turn the input string into an array of integers representing commands. However, since the compiler will be outputting an arbitrarily large number of commands, and since arrays in Arduino need to be initialized with a length, this could be a problem. </p> <p>I am not fluent in Arduino so I am hoping that an Arduino whiz can show me a quick solution. I have already come up with the suggested solution on my own in Python, however, my solution in Python has to do with the ability to change the length of lists on the fly. </p> <p>You will also notice that I posted the <a href="https://stackoverflow.com/questions/26303582/simple-compiler-design-help-variable-length-arrays-for-c">same question</a> in the C++ stackexchange. I am trying to write the same code for an Arduino and in C++. I know that Arduino code is based on C++, if the answer is the same in Arduino as it is in C++ that would be very helpful.</p>
<p>You may have more luck investigating standard C ways of dealing with this issue, instead of the common C++ methods. </p> <p>Although it is typically not advised, you can use malloc and free on the Arduino. This allows you to dynamically use memory. I would provide a more detailed code example than below but when using dynamic memory it can be hard to troubleshoot what is going on without the use of a library to simplify the process. I would strongly advise doing a little study and understanding both dynamic memory management, and the repercussions of doing so on the Arduino platform. A solid foundation in this will pay off tenfold in time saved when debugging.</p> <p>Note that you should check each time that you call malloc that it is successful</p> <p>These resources might help:</p> <ul> <li><p><a href="http://forum.codecall.net/topic/51010-dynamic-arrays-using-malloc-and-realloc/" rel="nofollow noreferrer">Dynamic Arrays</a></p></li> <li><p><a href="https://stackoverflow.com/questions/5607455/checking-that-malloc-succeeded-in-c">Check Malloc Succeded</a></p></li> <li><p><a href="http://forum.arduino.cc/index.php?topic=37796.0" rel="nofollow noreferrer">Malloc and Free on Arduino Discussion</a></p></li> <li><p><a href="https://arduino.stackexchange.com/questions/682/is-using-malloc-and-free-a-really-bad-idea-on-arduino">Is it a bad idea?</a></p></li> </ul> <p>Simple Example:</p> <pre><code>// Make a pointer to your array someType *A; // The size of your array, may be changed programmatically. int arraySize = 5; // Reserve memory for your array. A = malloc(arraySize * sizeof(someType)); // Use Array A[0] = someData; // Release A's memory when complete. free(A); </code></pre>
4545
|arduino-nano|relay|
How do you wire a ssr relay to a arduino nano
2014-10-11T06:24:11.670
<p>I am trying to wire a fss1-102z 5v ssr relay to my arduino nano but i cant get it to work here is my circuit. It stays stuck on and i cant get it to turn off.</p> <p><img src="https://i.stack.imgur.com/SEXkJ.png" alt="enter image description here"></p> <p>Bluetooth control code</p> <pre><code>char val; // variable to receive data from the serial port int ledpin = 2; // LED connected to pin 2 (on-board LED) void setup() { pinMode(ledpin = 2, OUTPUT); // pin 2 (on-board LED) as OUTPUT pinMode(ledpin = 3, OUTPUT); // pin 3 (on-board LED) as OUTPUT Serial.begin(9600); // start serial communication at 115200bps } void loop() { if( Serial.available() ) // if data is available to read { ; } val = Serial.read(); // read it and store it in 'val' if( val == 'a' ) // if 'a' was received led 2 is switched off { digitalWrite(ledpin = 2, HIGH); // turn Off pin 2 } if( val == 'A' ) // if 'A' was received led 2 on { digitalWrite(ledpin = 2, LOW); // turn ON pin 2 } if( val == 'b' ) // if 'b' was received led 3 is switched off { digitalWrite(ledpin = 3, HIGH); // turn Off pin 3 } if( val == 'B' ) // if 'B' was received led 3 on { digitalWrite(ledpin = 3, LOW); // turn ON pin 3 } //else (ledpin = 3, LOW) //set led pin 3 to low state if( val == 'C' ) // if 'C' was received led 2 on for 1 second { digitalWrite(ledpin = 2, LOW); // turn ON pin 2 delay(1000); // wait 1 second digitalWrite(ledpin, HIGH); // turn Off pin 2 } if( val == 'D' ) // if 'D' was received led 3 on for 1 second { digitalWrite(ledpin = 3, LOW); // turn ON pin 3 delay(1000); // wait 1 second digitalWrite(ledpin, HIGH); // turn Off pin 3 } if( val == 'E' ) // if 'E' was received led 2 on for 5 seconds { digitalWrite(ledpin = 2, LOW); // turn ON pin 2 delay(5000); // wait 500 milli seconds digitalWrite(ledpin, HIGH); // turn Off pin 2 } if( val == 'F' ) // if 'F' was received led 3 on for 5 seconds { digitalWrite(ledpin = 3, LOW); // turn ON pin 3 delay(5000); // wait 500 milli seconds digitalWrite(ledpin, HIGH); // turn Off pin 3 } if( val == 'G' ) // if 'G' was received turn led pin 2 on for 500ms then switch off and turn on pin 3 for 500 mili seconds then off { digitalWrite(ledpin = 2, LOW); // turn ON pin 2 delay(500); // wait 500mili second digitalWrite(ledpin, HIGH); // turn Off pin 2 digitalWrite(ledpin = 3, LOW); // turn ON pin 2 delay(500); // wait 500 mili second digitalWrite(ledpin, HIGH); // turn Off pin 2 } if( val == 'h' ) // if 'h' was received switch off all pins { digitalWrite(ledpin = 13, LOW); // turn Off pin 13 digitalWrite(ledpin = 2, HIGH); // turn Off pin 2 digitalWrite(ledpin = 3, HIGH); // turn Off pin 3 } if( val == 'H' ) // if 'H' was received switch pin 2 on and off 1000 times for(int i = 0; i &lt; 1000; i++) { digitalWrite(ledpin = 2, HIGH); // turn ON pin 2 delay (1000); //wait 1000 mili seconds digitalWrite(ledpin = 2, LOW); // turn Off pin 2 delay (1000); //wait 1000 mili seconds } } </code></pre>
<p>According to its <a href="http://www.ateco.it/pdf/art058_fss1.pdf" rel="nofollow noreferrer">datasheet</a>, the <code>FSS1-102Z</code> doesn't work with DC-voltage. Also the minimal voltage required is 50VAC. Here is the excerpt from the datasheet:</p> <p><img src="https://i.stack.imgur.com/TudEW.png" alt="enter image description here"></p>
4549
|arduino-ide|
I can't scroll Arduino IDE's example & scketch lists down
2014-10-11T11:38:17.700
<p>I have Arduino IDE 1.0.5 in win7 x64. I have so many library units. A pity that I can't scroll down to my other options. Is it Arduino.exe's problem or something else? How can I add triangle to scroll down and scroll up to see whole Sketchbook and Examples list? Thanks.</p> <p><img src="https://i.stack.imgur.com/feW18.png" alt="enter image description here"></p>
<p>Try using 1.5.+. It has scroll arrows to allow larger lists of menus, bigger than the screen. </p> <p>I find that most, if not all, sketches work equally well, if not better.</p> <p>Up to 1.5.6r2 uses the same version of compiler as 1.0.+'s. 1.5.7 and newer uses a new compiler, that is more sctrict. All stock libraries work. And well written 3rd parties work. I personally use 1.5 and test backwards to 1.0.</p> <p>There is a fork of 1.0 called ERW that has the scrolling. But 8t is becoming obsolete.</p>
4556
|serial|
What does the line "while (! Serial);" do in an Arduino program?
2014-10-11T16:44:54.813
<p>I'm new to Arduino, and I am trying a couple of tutorials. What does this line do in a program?</p> <pre><code>while (! Serial); </code></pre>
<p>On boards with an FT232 chip or other USB->Serial bridge chip (Uno, Mega, etc) it does absolutely nothing.</p> <p>On boards with a direct USB connection, such as the Leonardo or the Yùn it waits for an active serial connection to be established by the PC (i.e., for the serial port to be opened by a piece of software).</p> <p>When you open the serial port of a board like the Uno or Mega the whole board usually resets<sup>*</sup>, so opening the serial port allows you to see the first bits of the serial data. On the Leonardo etc it doesn't reset when you open the serial, so any serial output during the setup() function would be missed. Adding that line makes the board pause until you open the serial port, so you get to see that initial bit of data.</p> <p><sup>*) Unless you specifically write some software that doesn't assert DTR when you open the port</sup></p>
4565
|sensors|automatization|
How to sense snow and ice?
2014-10-12T11:45:42.483
<p>We are building an outdoor snow melting system for the pavement. It would be nice if it could turn on itself only when it is needed: if there is snow, ice in the surface or the pavement is wet and the temperature is below the freezing point. Is there a good way to detect if the surface of something is snowy, icy or wet?</p>
<p>cheap video camera with snow detection software. See <a href="https://core.ac.uk/download/pdf/188092083.pdf" rel="nofollow noreferrer">this article</a> for a start</p>
4566
|resistor|
Importance of resistor
2014-10-12T12:45:52.953
<p>I'm new to Arduino and also new to electronics. I'm following the tutorial <a href="http://arduino.cc/en/Tutorial/DigitalReadSerial" rel="nofollow noreferrer">here</a>. I'm not understanding the importance of the resistor in this schematic diagram. Can someone please help me on this?</p> <p><img src="https://i.stack.imgur.com/ilSHW.png" alt="enter image description here"></p>
<p>Check out the internal pull-up resistor (disconnected by default) for Arduino as well. Save yourself wiring up an extra resistor.</p> <pre><code>pinMode(5, INPUT_PULLUP); // Enable internal pull-up resistor on pin 5 </code></pre> <p>From SparkFun: <a href="https://learn.sparkfun.com/tutorials/pull-up-resistors/what-is-a-pull-up-resistor" rel="nofollow">Pull-up Resistors</a> </p>
4572
|flash|progmem|memory-usage|
PROGMEM: do I have to copy data from flash to RAM for reading?
2014-10-12T18:31:59.523
<p>I have got some difficulties understanding the memory management.</p> <p>Arduino documentation says, it is possible to keep constants like strings or whatever I don't want to change during runtime in program memory. I think of it as embedded somewhere in the code segment, which must be fairly possible inside a von-Neumann-architecture. I want to make use from that to make my UI menu on a LCD possible.</p> <p>But I'm bewildered by those instructions to just read and print data from program memory:</p> <pre><code>strcpy_P(buffer, (char*)pgm_read_word(&amp;(string_table[i]))); // Necessary casts and dereferencing, just copy. Serial.println( buffer ); </code></pre> <p>Why on earth do I have to copy the damn content to RAM before accessing it? And if this is true, what happens to all the code then? Is it also loaded to RAM before execution? How is the code (32kiB) handled then with only 2kiB RAM? Where are those little goblins carrying floppy disks?</p> <p>And even more interesting: What happens to literal constants like in this expression:</p> <pre><code>a = 5*(10+7) </code></pre> <p>are 5, 10 and 7 really copied to RAM before loading them into registers? I just can't believe that.</p>
<blockquote> <p>Arduino documentation says, it is possible to keep constants like strings or whatever I don't want to change during runtime in program memory. </p> </blockquote> <p><strong>All</strong> constants are initially in program memory. Where else would they be when the power is off? </p> <blockquote> <p>I think of it as embedded somewhere in the code segment, which must be fairly possible inside a von-Neumann-architecture. </p> </blockquote> <p>It's actually <a href="https://en.wikipedia.org/wiki/Harvard_architecture" rel="nofollow">Harvard architecture</a>.</p> <blockquote> <p>Why on earth do I have to copy the damn content to RAM before accessing it?</p> </blockquote> <p>You don't. In fact there is a hardware instruction (LPM - Load Program Memory) which moves data directly from program memory into a register.</p> <p>I have an example of this technique in <a href="http://www.gammon.com.au/forum/?id=11608" rel="nofollow">Arduino Uno output to VGA monitor</a>. In that code there is a bitmapped font stored in program memory. It is read from that on-the-fly and copied to the output like this:</p> <pre><code> // blit pixel data to screen while (i--) UDR0 = pgm_read_byte (linePtr + (* messagePtr++)); </code></pre> <p>A disassembly of those lines shows (in part):</p> <pre><code> f1a: e4 91 lpm r30, Z+ f1c: e0 93 c6 00 sts 0x00C6, r30 </code></pre> <p>You can see that a byte of program memory was copied into R30, and then immediately stored into the USART register UDR0. No RAM involved.</p> <hr> <p>However there is a complexity. For normal strings the compiler expects to find data in RAM not PROGMEM. They are different address spaces, and therefore 0x200 in RAM is something different from 0x200 in PROGMEM. Thus the compiler goes to the trouble of copying constants (like strings) into RAM at program startup, so it doesn't have to worry about knowing the difference later on.</p> <blockquote> <p>How is the code (32kiB) handled then with only 2kiB RAM?</p> </blockquote> <p>Good question. You won't get away with having more than 2 KB of constant strings, because there won't be room to copy them all.</p> <p>That's why people who are writing things like menus and other wordy stuff, take extra steps to give the strings the PROGMEM attribute, which disables them being copied into RAM.</p> <blockquote> <p>But I'm bewildered by those instructions to just read and print data from program memory:</p> </blockquote> <p>If you add the PROGMEM attribute you have to take steps to let the compiler know that these strings are in a different address space. Making a complete (temporary) copy is one way. Or just print directly from PROGMEM, a byte at a time. An example of that is:</p> <pre><code>// Print a string from Program Memory directly to save RAM void printProgStr (const char * str) { char c; if (!str) return; while ((c = pgm_read_byte(str++))) Serial.print (c); } // end of printProgStr </code></pre> <p>If you pass this function a pointer to a string in PROGMEM, it does the "special read" (pgm_read_byte) to pull the data from PROGMEM rather than RAM, and the prints it. Note that this takes one additional clock cycle, per byte.</p> <blockquote> <p>And even more interesting: What happens to literal constants like in this expression <code>a = 5*(10+7)</code> are 5, 10 and 7 really copied to RAM before loading them into registers? I just can't believe that.</p> </blockquote> <p>No, because they don't have to be. That would compile into a "load literal into register" instruction. That instruction is already in PROGMEM, so the literal is now dealt with. No need to copy it to RAM and then read it back.</p> <hr> <p>I have a lengthy description of these things on the page <a href="http://www.gammon.com.au/progmem" rel="nofollow">Putting constant data into program memory (PROGMEM)</a>. That has example code for setting up strings, and arrays of strings, reasonably easily. </p> <p>It also mentions the F() macro which is an easy way of simply printing from PROGMEM:</p> <pre><code>Serial.println (F("Hello, world")); </code></pre> <p>A bit of preprocessor complexity lets that compile into a helper function which pulls the bytes in the string from PROGMEM a byte at a time. No intermediate use of RAM is required.</p> <p>It is easy enough to use that technique for things other than Serial (eg. your LCD) by deriving the LCD printing from the Print class.</p> <p>As an example, in one of the LCD libraries I wrote, I did exactly that:</p> <pre><code>class I2C_graphical_LCD_display : public Print { ... size_t write(uint8_t c); }; </code></pre> <p>The key point here is to derive from Print, and override the "write" function. Now your overridden function does whatever it needs to output a character. Since it is derived from Print you can now use the F() macro. eg.</p> <pre><code>lcd.println (F("Hello, world")); </code></pre>
4580
|programming|softwareserial|
Error: 'SofwareSerial' does not name a type
2014-10-13T11:44:01.197
<p>I have trouble compiling this sketch. The error I get is</p> <blockquote> <p>'SoftwareSerial' does not name a type</p> </blockquote> <p>Any ideas how could I fix it?</p> <pre><code>#include SoftwareSerial.h SoftwareSerial mySerial(10, 11); // RX, TX void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } Serial.println("Ready!"); // set the data rate for the SoftwareSerial port // for HC-05 use 38400 when poerwing with KEY/STATE set to HIGH on power on mySerial.begin(9600); } void loop() // run over and over { if (mySerial.available()) Serial.write(mySerial.read()); if (Serial.available()) mySerial.write(Serial.read()); } </code></pre>
<pre><code>#include "SoftwareSerial.h" worked instead of </code></pre> <p><code>#include &lt;SoftwareSerial.h&gt;</code> ie " " not &lt;></p>
4583
|c++|
Simple compiler design help: Variable length arrays?
2014-10-10T16:05:09.923
<p>I'm trying to write a simple compiler in C++ for a language that I am making up for my lab. The compiler will have to be able to turn a string like this:</p> <pre><code>"do command_one 3 times" </code></pre> <p>into a data structure that represents this:</p> <pre><code>&lt;command_one&gt;, &lt;command_one&gt;, &lt;command_one&gt; </code></pre> <p>it should also be able to turn something more complicated like this:</p> <pre><code>"do do c_one do c_two 2 times 2 times c_thr 2 times" </code></pre> <p>into a data structure that represents this:</p> <pre><code>&lt;c_one&gt; &lt;c_two&gt; &lt;c_two&gt; &lt;c_one&gt; &lt;c_two&gt; &lt;c_two&gt; &lt;c_thr&gt; &lt;c_one&gt; &lt;c_two&gt; &lt;c_two&gt; &lt;c_one&gt; &lt;c_two&gt; &lt;c_two&gt; &lt;c_thr&gt; </code></pre> <p>Another function will then read the commands out one by one.</p> <p>These examples show all of the functionality that I would want from the compiler. </p> <p>I'm having design issues for the compiler that I want to create. Initially, I just wanted to do some string manipulation and turn the input string into an array of integers representing commands. However, since the compiler will be outputting an arbitrarily large number of commands, and since arrays in C++ need to be initialized with a length, this could be a problem. </p> <p>I am not fluent in C++ so I am hoping that a C++ whiz can show me a quick solution. I have already come up with the suggested solution on my own in Python, however, my solution in Python has to do with the ability to change the length of lists on the fly. </p> <p>EDIT: I am also intending to use this code for an Arduino, which supports C++ code but not the standard libraries. I found the vector solution to work in my C++ code, but it will not work in the Arduino interface. Is there a way to do the compiling WITHOUT using vectors? </p>
<p>After Edit:</p> <p>Since you cant use vectors ...</p> <p>... or use variable length arrays, if the compiler you are using it, supports it.</p> <p>... the other viable solution is to get your own list or vector library, either from an existing open source library or implementing your own.</p> <p>Cheers.</p>
4591
|motor|pwm|
Controlling ESC with Arduino
2014-10-11T23:57:58.063
<p>I want to control these motors: <a href="http://www.hobbyking.com/hobbyking/store/uh_viewitem.asp?idproduct=6247&amp;aff=61689" rel="nofollow">hexTronik DT750 Brushless Outrunner 750kv</a> with this battery: <a href="http://www.hobbyking.com/hobbyking/store/uh_viewItem.asp?idProduct=8934&amp;aff=61689" rel="nofollow">Turnigy 2200mAh 3S 25C Lipo Pack</a> and these ESCs: <a href="http://www.hobbyking.com/hobbyking/store/uh_viewItem.asp?idProduct=4312&amp;Product_Name=TURNIGY_Plush_18amp_Speed_Controller&amp;aff=61689" rel="nofollow">TURNIGY Plush 18amp Speed Controller</a>.</p> <p>I am new to this field of driving brush-less motors. Can someone tell me if I need anything else? Will this set-up work without anything getting destroyed?</p>
<p>I 've been working on an autonomous arduino quadcopter for about 7 months now and I have a few tips for you.</p> <p>1) your setup seems fine as long as your motors aren't going to draw more amps than your ESC can supply, but It is always a good idea to buy ESCs with a higher "max amps" than your motors draws. I would choose 25 amp max ESCs or higher.</p> <p>2) In order to control the motors via PWM, I use the Servo library because you get a resolution from 700-2000 as opposed to "analogWrite" which gives a default resolution of 0-255.</p> <p>3) your ESC probably has a minimum pulse width value before it will start. I would recommend writing a program that gives you the ability to plug in values from 700-2000, and use the program to slowlly find that arming pulse width value. Mine is 1110 for reference. </p> <p>If you have anymore questions, I will glady answer them. </p> <p>May I ask, what is your project?</p>
4595
|teensy|
Maxbotixs LV-EZ4 analog read question
2014-10-13T20:37:20.120
<p>I am using an external 5 volt power supply to power my Sonar, and I am using a Teensy 3.1 to read in analog signal from the sonar. my question is since the teensy is only 3.3v tolerant with analog in, is it safe to use with the maxbotix sonar? </p>
<p><em>Converted Gerben's comment to an answer</em></p> <hr> <p>That is not safe. Maximum voltage on the analog pins is 3.3v, according to the datasheet. But why don't you power it from 3.3v? Minimal voltage for that unit is 2.5v. And it uses only 2mA.</p>
4596
|arduino-uno|atmega328|
ATMega328P not running sketch in standalone (works in Uno R3 Board though)
2014-10-13T21:58:13.010
<p>I bought an ATMega328P-PU and burned OptiBoot onto it using a second <em>Arduino Uno R3</em> with great success.</p> <p>I then put the microcontroller back on the (empty) Uno R3 (DIP) Board for programming, connected USB and uploaded the blink sketch successfully.</p> <p>Now to the weird stuff:</p> <p><code>Blink</code> works on the Arduino Board itself, but if I pull it out and stick it into my breadboard, the program seems to not start. Here are some facts:</p> <ul> <li>happens with or without external crystal <code>16.000</code> <em>(Pin 9-10)</em></li> <li>happens with or without the 22pF capacitors from <code>crystal</code> to <code>GND</code> <em>(9-GND, 10-GND)</em></li> <li>happens with Fuses set to internal OSC or to external clock <em>(Uno default)</em></li> <li>happens with or without the <code>ADC VCC</code> <em>(Pin 20)</em> and <code>REFERENCE</code> <em>(Pin 21)</em> Pins @ 5V</li> <li>happens on 5V and on 3V3</li> <li>happens with or without external Pullup on <code>RESET</code> Pin (1)</li> <li>Most of the output Pins sit at <code>0.8 V</code></li> </ul>
<h2>I found the solution by accident.</h2> <p>While I used my multimeter to measure the voltages between GND and the Pins (for the last fact), I noticed the program running at weird speeds. I. e. the LED started blinking.</p> <h2>What did I measure?</h2> <p>Actually I was just measuring one of the <code>crystal</code> pins <em>(Pin 9 or 10)</em>. The sketch went running for a few seconds and very different speeds and then stopped.</p> <p>This small change in voltage gave the ATMega the <code>clock</code> signal it needs to step through the program.</p> <p>Maybe I need less capacitance of the two capacitors as mentioned in the comments. I will update the answer with more information later on.</p> <h2>The perfect solution</h2> <p>As pointed out in the comments, I really chose the wrong capacitors. It worked without, but we want the stability so use a bright light and a magnifying glass if you are unsure. Really, do it.</p>
4610
|arduino-uno|motor|pwm|transistor|
How to eliminate noise from PWM controlled 12V fan at low speed
2014-10-15T07:45:16.907
<p>I am trying to build a simple fan controller (single fan). So far I have successfully created a circuit which powers the fan with an external 12v DC adapter and added a transistor (NPN) to switch it on and off. The transistor is connected to a PWM port on the Arduino. </p> <p>When putting <code>HIGH</code> on the port the fan works perfectly at high speed, but when I want to lower the speed (say <code>analogWrite(fanPin, 150)</code>) it starts to make a humming noise. I believe this is caused by the use of PWM.</p> <p>What is the best way to control the speed of the fan without (too much) noise?</p> <p>ps. The fan is a Cooler Master 3-wire PC fan. Transistor is a P2N2222A.</p> <p><strong>Update</strong>: Here is the schema I am using:</p> <p><img src="https://i.stack.imgur.com/UIYfW.png" alt="schema"></p>
<p>25kHz power PWM solved this problem for my 3-pin fan. Diode had no effect on noise, it fixes another problem (EMI).</p>
4612
|sensors|
Detecting grass, pavement, gravel
2014-10-15T11:16:20.953
<p>I think about building my own robotic mower, therefore I would like to detect if the surface the mower in moving on is grass, pavement, gravel ... etc.</p> <p>Which sensors would be the best choice in order to achieve this?</p> <p>The benefits:</p> <ul> <li>no parimeter wire to bury </li> <li>possible lawn edge detection (here most mowers fail to do a good job)</li> </ul>
<p>I have found this DIY mower page (where they apparently already implemented a grass sensor). <a href="http://www.ardumower.de/index.php/en/ardumower-topics/sensors/lawn-sensor" rel="nofollow">Grass sensor</a>. Other useful info can also be found (mixed in english and german).</p> <p>They are measuring the capacity of the underground in about 2cm (1inch) height. </p> <p>On gravel or other hard material this is near 0 (as the sensor is in the air). On grass the value is higher.</p> <p>Haven't though of this solution, should be the way to go.</p>
4617
|memory-usage|
Can arduino create a file in its memory?
2014-10-15T14:24:10.983
<p>I am an arduino enthusiast and i am new to it.just wanted to know weather the micro processor itself could create a file in its memory while its is running. I know that it is possible to read a write from a file in c++ but is it possible to do so in an arduino (while it's running).</p>
<p>To answer the original question: Basically, yes, you can write libraries to implement a file system using the memories of an embedded microcontroller. <br> However, if it's feasible highly depends on the controller architecture and its peripherals. <br> Some of them (e.g. the one on Arduino Due) allow Flash reprogramming while an application is running from Flash.<br> Others require to have the application running in a special boot block or even in RAM when accessing the Flash for writing (this should be the case on an Arduino Uno)<br> And others don't allow Flash accesses from application at all.<br></p> <p>Anyway:<br> The use of this for your purpose is very little, because the interface to the PC would also have to support the file system (for example, you could implement a FTP server and use an Ethernet connection...). <br>Therefore, the SD card approach is surely a very good suggestion.</p>
4623
|arduino-uno|power|voltage-level|servo|current|
How do voltage and resistance work for two 5v servos when using an external 12v power supply?
2014-10-16T03:31:13.507
<p>I have a 12v/1.5 amp barrel plug power supply on my Arduino Uno. I have two servos that say they are rated for 4.8v to 6v, but no amps are specified. When my circuit is configured as it is in this image, it appears to work fine. (In my test sketch, I'm constantly and simultaneously rotating them from 0 - 180 degrees and then in reverse.) </p> <p>But I don't understand why it works. I assumed the 5v pin can only supply 5v of total power to the whole configuration. Is it instead supplying a regulated 5v at as needed between both servos from a total pool of 12v (presumably up to 10v at once)? Do I need voltage regulation? Shouldn't I have to know the amps for the servo(s) and use some sort of resistance?</p> <p>Thanks for any information and advice you can share on learning about the concepts underlying a situation like this.</p> <p><img src="https://i.stack.imgur.com/bkXNT.png" alt="Running two servos from one 12v power supply"> </p> <p>Update: I ultimately modified my approach based on the feedback received here by wiring a separate 5v/2a power supply to the breadboard for the two servos, and wiring the rest of the circuit appropriately (using a common ground, etc.). </p>
<p>Addition to Ignacio. Explanation from real life.</p> <p>Gregir, look at your home devices like TV, micro wave, fridge and so on. They all need 220-230 V AC and you can plug all them to one socket. As Ignacio said voltage doesn't plus. The current does plus, for ex. you have 2 servos connected in parralel, both 5V, no load current 0.1A. So to run them with no load you will have to supply 5V and 0.1+0.1=0.2A.</p> <p>I tried to explain at very basic level ;) </p>
4630
|arduino-uno|
Arduino Uno suddenly not recognized in Windows 8.1 (code 43)
2014-10-16T16:53:51.697
<p>I had my Arduino Uno connected to an external 12 V supply for 2-3 hours as I was working on other parts of my project. Suddenly the voltage from pin 9 which I was monitoring in the oscillator dropped down to 0 approximately. </p> <p>I went on removing the external supply. The board was very very hot. I then connected the USB to my laptop and I got an error 43 (Windows did not allow the device to connect because it was reporting problems). I can't load any program of course. The 5 V pin works but it outputs a voltage lower than usual (at about 3.9 V). When I connect the external supply the 5 V pin outputs full voltage. </p> <p>Any idea? Any fix?</p>
<p>I've been dealing with the same issue, and have resolved it in a manner similar to random approach described above.</p> <p>Drivers will get corrupted as we all know. But if you want to get past that Code 43 error, you need to have the arduino unplugged from the USB when reinstalling. Otherwise windows will bind the USB.inf generic driver to the device, which prevents the install of the CH341SER driver.</p> <p>So unplug USB, delete the unknown device via Device mgr, run the CH341SER, *then plug in the USB cable. So I think that random approach worked not because the 9v reset was done unplugged, but because that was first chance (unplugged) that the CH341SER driver had to install without resources bound to generic USB.inf driver.</p>
4638
|sensors|communication|
Wireless Sensor (IMU) to Arduino
2014-10-17T19:36:16.980
<p>I was doing some research about this subject and I only have more questions than answers.</p> <p>I want a little IMU sensor (I don't know which hardware I should get) that sends data wirelessly to my Arduino.</p> <p>The sender part (IMU + sender + battery) should be small (tennis ball size is fine) and the receiving part should be an Arduino.</p> <p>What should I buy? How can I achieve this? I was looking at a lot of ideas: Xbees, bluetooth, radio receivers, Arduino Nano, etc.</p> <p>My focus is on the Arduino code, I just need that the IMU sends data at least at a ratio of 10ms.</p> <p>As a plus I would love to have more than one Wireless IMU sensor connected to my Arduino.</p>
<p>You have not really given enough specifications for any choice of radio to make a difference in your scenario. Any list of products would be very long, overly summarized, and not relevant in a month, So I'll try and outline the thought process I would take in finding the fit for a project I was making.</p> <p><strong>Radio:</strong> Which type of radio to choose will depend on a lot of specific factors, but its more than likely that multiple options will work perfectly. You seem to know the major methods, Xbee, bluetooth, Wifi, and for very long distances, GSM.</p> <p>You should consider the problem, define what you need by looking at the amount of data per second you want sent, the necessary range, the power you have available in the battery, any region specific laws, and anything else you can think of needing. Also consider if you really need an arduino as the receiver, or if you have a Bluetooth equipped laptop or wireless router on hand that could take that roll for you. Then look around at sparkfun or wherever and find the cheapest, most popular method that fits the bill. </p> <p><strong>IMU:</strong> Many IMU's exist with more or less the exact same features, so I will recommend a similar process. Look at the power consumption, output rate, sensitivity, and communication method you project needs, and find the cheapest and/or best rated item at your preferred electronics retailer that fits the bill. the MPU6000's are popular these days. The altIMUv4 has a magnetometer and barometer included as well. Shop around.</p> <p>You will most likely want to put an arduino nano/micro/trinket/whatever with the IMU to translate to your communication method. Some radios work with UART serial, but not many IMU's output like this. Those that do cost more because they have a coprocessor on board. Consider if buying a co-processor equipped board will make your sensor processing easier before you discount it for the elevated price. In depth sensor fusion gets pretty hairy, and for some, not having to worry about it could be worth $50. </p>
4640
|c++|
problem using std::map. Are there known obstructing macros?
2014-10-17T22:57:32.043
<p>I have a header file, where I try to collect global variable declarations. When trying to typedef a map I get the following error:</p> <pre><code>n file included from Dis0_10.ino:7: /var/folders/jl/nv1qvh6n569cxq9xxfd6dx980000gn/T/build8295701509021940161.tmp/globals.h:23: error: expected initializer before '&lt;' token </code></pre> <p>relevant code snippets from global.h are:</p> <pre><code>#ifndef GLOBALS #define GLOBALS #include &lt;map&gt; </code></pre> <p>...</p> <pre><code>typedef std::map&lt;uint8_t,uint8_t&gt; memmap_t; </code></pre> <p>I have no clue, why this statement should fail. I consider it rather straight forward. So I think there must be some problems of <a href="https://stackoverflow.com/questions/6558697/c-map-expected-initializer-before-token">this kind here</a>. Or am I missing another include?</p>
<p>The C++ standard library is not available for arduino. </p> <p>Some implementations of similar containers or certain functions exist on the web, but for the most part the standard library is impractical on a device with such small amounts of both RAM and program memory.</p> <p>An implementation of SGI STL for AVR has been documented here: <a href="http://andybrown.me.uk/wk/2011/01/15/the-standard-template-library-stl-for-avr-with-c-streams/" rel="nofollow">http://andybrown.me.uk/wk/2011/01/15/the-standard-template-library-stl-for-avr-with-c-streams/</a></p> <p>map is mentioned as being particularly impractical for anything less than an arduino mega(1280). An example of maps working is included on the page so it seems like a good lead if you really must use one, but I've never done this myself so I cant guarantee it still works.</p>
4642
|arduino-mega|arduino-duemilanove|
Use Arduino Mega to program Arduino Duemilanove
2014-10-18T06:56:19.897
<p>I hava an Arduino Duemilanove but I think that its FTDI chip is crashed.</p> <p>I have an Arduino Mega too, so can I use it to program my Duemilanove?</p>
<p>Yes, this is not an uncommon activity. This is called using an Arduino as an In-System Programmer (ISP)</p> <p>This page has the information and Arduino program you need. You'll need to adjust for the Arduino Mega pin differences, but that's fairly easy. <a href="http://arduino.cc/en/Tutorial/ArduinoISP" rel="nofollow">http://arduino.cc/en/Tutorial/ArduinoISP</a></p> <p>Where the ArduinoISP page references pin 13, on the Mega it's pin 52. Where the ArduinoISP page references pin 12, on the Mega it's pin 50. Where the ArduinoISP page references pin 11, on the Mega it's pin 51. Where the ArduinoISP page references pin 10, on the Mega it's pin 53.</p> <p>Otherwise you should be able to connect the Mega to the patient in the same way as described, load the ArduinoISP sketch into the Mega, preferably from the GitHub repository linked in the article (<a href="https://github.com/rsbohn/arduinoisp" rel="nofollow">https://github.com/rsbohn/arduinoisp</a>).</p>
4649
|sensors|
Sense Whether Circuit is Closed
2014-10-19T04:03:21.263
<p>How can you sense a closed circuit? I want to have 4 pins with disconnected wires and when touched with a fifth wire play a specific note on a piezo buzzer until disconnected again.</p> <p><a href="http://www.instructables.com/id/Capacitive-Touch-Arduino-Keyboard-Piano/?ALLSTEPS" rel="nofollow">This project</a> loops through several keys and checks whether they are being touched using the <a href="http://playground.arduino.cc/Main/CapacitiveSensor?from=Main.CapSense" rel="nofollow">Capactive Sensor library</a>. I want to do something similar, but not with capacitive sensing. Alternatively, it may work to have the buzzer always trying to play a note, but only sounds when one of the 4 circuits is close. I'm just not sure how that would work in the code.</p> <p>Here is their code that uses capactive sensing:</p> <pre><code>#include &lt;CapacitiveSensor.h&gt; #include "pitches.h" #define COMMON_PIN 2 // The common 'send' pin for all keys #define BUZZER_PIN A4 // The output pin for the piezo buzzer #define NUM_OF_SAMPLES 10 // Higher number whens more delay but more consistent readings #define CAP_THRESHOLD 150 // Capactive reading that triggers a note (adjust to fit your needs) #define NUM_OF_KEYS 8 // Number of keys that are on the keyboard // This macro creates a capacitance "key" sensor object for each key on the piano keyboard: #define CS(Y) CapacitiveSensor(2, Y) // Each key corresponds to a note, which are defined here. Uncomment the scale that you want to use: int notes[]={NOTE_C4,NOTE_D4,NOTE_E4,NOTE_F4,NOTE_G4,NOTE_A4,NOTE_B4,NOTE_C5}; // C-Major scale // Defines the pins that the keys are connected to: CapacitiveSensor keys[] = {CS(3), CS(4), CS(5), CS(6), CS(7), CS(8), CS(9), CS(10)}; void setup() { // Turn off autocalibrate on all channels: for(int i=0; i&lt;8; ++i) { keys[i].set_CS_AutocaL_Millis(0xFFFFFFFF); } // Set the buzzer as an output: pinMode(BUZZER_PIN, OUTPUT); } void loop() { // Loop through each key: for (int i = 0; i &lt; 8; ++i) { // If the capacitance reading is greater than the threshold, play a note: if(keys[i].capacitiveSensor(NUM_OF_SAMPLES) &gt; CAP_THRESHOLD) { tone(BUZZER_PIN, notes[i]); // Plays the note corresponding to the key pressed } } } </code></pre>
<p>Connect your fifth wire to ground. Set the four inputs to <code>INPUT_PULLUP</code>. The four inputs will default <code>HIGH</code>, and be pulled <code>LOW</code> when connected to the ground wire.</p>
4652
|serial|arduino-mega|
USB D+ D- to Arduino Mega RX TX
2014-10-19T11:47:11.280
<p>Is it possible to directly communicate USB D+ D- to Arduino Mega serial port TX RX?</p>
<p>No, D+/- are high frequency USB signals. TX/RX is 5V UART protocol, i.e. compeletely different. But you can e.g. use AT90USB128x processor to avoid 16u2 bridge. The prosessor is not so mighty as 2560 but it's cheaper and simplifies design.</p>
4664
|arduino-uno|hardware|
Connecting a Long Stem Thermometer to an Arduino to automate the recording of temperature in an experiment
2014-10-20T14:18:08.080
<p>Is there a way to connect and read the output of a long stem thermometer like this one to an Arduino?</p> <p><img src="https://i.stack.imgur.com/oydBw.jpg" alt="enter image description here"></p>
<p>Interfacing with a temperature sensor such as the DS18B20 (<a href="https://www.sparkfun.com/products/11050" rel="nofollow">https://www.sparkfun.com/products/11050</a>) would be much simpler than trying to interface with a thermometer with unknown internals.</p> <p>Theoretically, yes, you can use the thermometer you posted, but it won't be simple. The only way to know what you would have to do to interface with it is to open it up and see what's inside. You would still have to calibrate it though to make any sense of the readings you get from it.</p>
4666
|voltage-level|servo|electronics|
Where can I find beginner resources on using voltage regulators with Arduino circuits?
2014-10-20T18:06:31.327
<p>I'm trying to concurrently learn electronics and Arduino, and have recently moved from simply powering LEDs to servos. In all my attempts with servos and reading about them (especially multiple ones, and when using external power supply plugged into the board), experienced users often mention you use voltage regulators.</p> <p>I've seen some Arduino schematics with servos and voltage regulators, most that include some capacitors, but I can't seem to find any tutorials or resources that explain why, when and how to use these parts when learning electronics &amp; Arduino. (I'd like to go from there to transistors, mosfets, etc.)</p>
<p>In order to get a smooth signal to your power regulator you should use some capacitors before and after the voltage regulator. It will look something like this when you use the 7805 voltage regulator.</p> <p><img src="https://i.stack.imgur.com/Z2L6V.png" alt="7805 Voltage Regulator"></p> <p>Note: This schematic is from a dutch website. Uin means Vin and Uuit means Vout. C2 and C3 are bipolar capacitors.</p> <p>It's also smart to put a diode before the voltage regulator to make sure the voltage flows only to one direction. The values of C1, C2, C3 and C4 and pretty standard and coul be used for the other Voltage regulators as well. </p> <p>The voltage Regulators come in different fixed values and tey have a minimum and maximum voltage they can handle. Here's a small table of the most common VR's with their minimum input voltages.</p> <pre><code>Part Number Output Voltage (V) Minimum Input Voltage (V) 7805 +5 7.3 7806 +6 8.3 7808 +8 10.5 7809 +9 11.5 7810 +10 12.5 7812 +12 14.6 7815 +15 17.7 7818 +18 21.0 7824 +24 27.1 </code></pre> <p>Also note that the output currents of these Voltage Regulators listed above is max 1A. When they're called like 78S05 or 78S09 it'll be a 2A Voltage Regulator.</p> <p>Another thing that could be important when you're using the minimum input voltages. If you put a diode before the Voltage Regulator there will be a small voltage drop. For a 1N4007 the voltage drop will be around the 0.5V. The voltage drop will only occur before the voltage regulator though, so when you don't use the minimal input values you don't have to mind about it.</p>
4675
|arduino-uno|button|
Resistance in Switch (negative vs positive logic)
2014-10-21T21:54:22.897
<p><img src="https://upload.wikimedia.org/wikipedia/commons/6/6f/Positive_Negative_Logic_connection_of_Switch_with_Microcontroller_pin.png" alt="Positive Negative Logic connection of Switch"></p> <p>I tried in my Arduino the negative logic to get a digital input from a switch (with 10 KΩ resistance). If I want to use the positive logic what kind of resitance I have to use? For me seems that 10KOhm it to big and probably a smaller resistor should be used. How do we compute the value of the resistor? The schemes of Negative and Positive Logic from <a href="http://users.ece.utexas.edu/~valvano/Volume1/E-Book/C8_SwitchLED.htm" rel="nofollow">Valvano's notes/ebook - University of Texas</a> gives 10 kΩ in both cases. Is it correct?</p>
<p>From a pure electronics viewpoint, there is no real difference between both circuits, the difference will be handled by your code running on the MCU, as a close switch will either be <code>HIGH</code> or <code>LOW</code> depending on the logic you used to wire your switch.</p> <p>The resistor must be present for 2 reasons:</p> <ul> <li>to avoid producing a shortcut between <code>+5V</code> and <code>GND</code> when the switch is closed, without it the shortcut would probably damage your power supply circuitry (if both pins are directly taken from Arduino, that would mean damaging Arduino supply circuits)</li> <li>to make the voltage pin attached to the pin the "<em>winner</em>" of both voltage pins when the switch is closed, ie that pin will provide the level to Arduino input pin</li> </ul> <p>The value of the resistor should be:</p> <ul> <li>high enough to limit the current between <code>+5V</code> and <code>GND</code> when the switch is closed, preventing damage and limiting overall power consumption of your circuit</li> <li>not too high to allow providing a voltage level to the input pin</li> </ul> <p>Using 10k means that, applying Ohm's law, when closing the switch, a 0.5mA current would flow from <code>+5V</code> to <code>GND</code>, which is generally acceptable in terms of consumption and cwill not damage your power supply.</p> <p>Note that the input pin is "<strong>high impedance</strong>" which means it has no voltage level if not connected to anything, and it does not supply or sink any current (or more accurqtely a negligible current only).</p> <p>Finally, it is good to know that Arduino MCU offers the <code>INPUT_PULLUP</code> mode for digital pins, where an internal resistor pulls up the pin input to 5V. This enables you to directly connect your switch between the pin and <code>GND</code>. So you just have to code:</p> <pre><code>pinMode(XXX, INPUT_PULLUP); </code></pre> <p>instead of:</p> <pre><code>pinMode(XXX, INPUT); </code></pre> <p>For information, according to ATmega328P datasheet (the MCU of Arduino UNO), those internal pullup resistors have a value between 20k and 50k.</p>
4681
|arduino-uno|i2c|
How do functions outside of void loop work?
2014-10-22T11:56:15.507
<p>I am used to Arduino sketches with a <code>void setup()</code> part that runs once, and a <code>void loop()</code> part that keeps looping. What happens when you have void functions outside of the main <code>void loop()</code>? Will these all keep looping in parallel or do they run one after the other? Or do certain void functions only run once certain criteria has been met (like a while loop)?</p> <p>For example in the code below, when will the <code>void receiveData(int byteCount)</code> and the <code>void sendData()</code> functions run? </p> <pre><code>//I2C_test //This code demonstrates communication via an I2C bus between a raspberry pi and an arduino. //When the Raspberry pi (master) sends data to the Arduino (slave), the Arduino uses this //data to control a motor. After the Arduino has recieved data from the master, it then collects //data from the external environment via a sensor and sends this data back to the Raspberry pi. #include &lt;Wire.h&gt; int number = 0; //Declare variables int val = 0; void setup() { //Anything between the curly brackets runs once when the arduino is turned on or reset pinMode(0, INPUT); //Set pin 0 as input and 3 as output pinMode(3, OUTPUT); Serial.begin(9600); //Set the data rate for serial transmission at 9600bps Wire.begin(0x04); //Initiate the Wire library, join the Arduino as a slave, and specify its 7 bit slave address Wire.onReceive(receiveData); //Define callbacks for i2c communication Wire.onRequest(sendData); } void loop() { //The code between the curly brackets keeps repeating delay(100); } void receiveData(int byteCount) { while(Wire.available()) { number = Wire.read(); //Set the variable "number" to the data sent by the master analogWrite(3, number); //Write this number to pin 3 (PWM). This controls the motor speed } val = analogRead(0); //Read the voltage on pin 0 (connected to the sensor). Map input voltages between 0 and 5 volts into integer values between 0 and 1023 } void sendData() { Wire.write(val); //Send the data read from the sensor to the master. } </code></pre>
<p>I can't comment on Dee's response. The actual code that is executed in the main loop is <a href="https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/main.cpp" rel="nofollow noreferrer">here</a>:</p> <pre><code> int main(void) { init(); initVariant(); setup(); for (;;) { loop(); if (serialEventRun) serialEventRun(); } return 0; } </code></pre> <p>And yes, <code>setup()</code> gets called once and <code>loop()</code> is being called repeatedly (together with some serial stuff).</p>
4687
|arduino-uno|
Is my Arduino UNO fried?
2014-10-22T20:19:21.293
<p>The title sums it all up. While testing the new proximity detector I bought off of Amazon, a spark flew from some random area and my Arduino's On LED went off while its Loop LED stayed in a dim state. I am here to ask you guys if this basically counts my Arduino as fried and that I need a new one, or if I should wait and see if it works again, being that I wrote this 5 minutes after the thing happened. </p> <p>Thanks in advance,</p> <p>afroraydude</p>
<p>It's hard to tell without further testing. Do the following:</p> <ol> <li>Remove the Uno from the faulty circuit, making sure you remove all the wiring from the Arduino board.</li> <li>Plug the Uno into the USB port. Does the ON LED light up? Does the built-in LED on D13 blink three times? (this should happen if you had the optiboot bootloader)</li> <li>Remove the USB cable and plug the Uno to a 9V source through the barrel power connector. Do the same test above.</li> <li>Can you upload the Blink sketch? If you can, does it make D13 LED blink once a second?</li> </ol> <p>Report your findings by updating your question.</p>
4696
|serial|reset|
How to reset Arduino from software
2014-10-23T15:04:44.637
<p>As you know, the Arduino IDE resets the Arduino when the Serial Monitor is opened. I want also my program to do it. But I don't know how.</p> <p>I examined the source code of the Arduino IDE (Serial.java &amp; SerialMonitor.java), but I can't find where it sends the reset command. Where is it?</p> <p>I use C# to communicate with serial.</p>
<p>OK, I have solved this by sending DSR pulse as seen on code below: </p> <pre><code>mySerial.DtrEnable = true; mySerial.Open(); Thread.Sleep(1000); mySerial.DtrEnable = false; </code></pre>
4700
|programming|library|avr|sleep|
error: ‘sleep’ was not declared in this scope
2014-10-24T01:48:50.583
<p>I am trying to use the sleep function in lieu of <code>delay()</code>, but when I include <code>sleep()</code>, I get <code>Sweep.cpp:60:10: error: ‘sleep’ was not declared in this scope</code></p> <p>I read some place, about <code>#include &lt;avr/sleep.h&gt;</code> but that is a fail.</p> <pre><code>#include &lt;avr/sleep.h&gt; void setup() { } void loop() { digitalWrite(13, HIGH); // set the LED on sleep(1); // wait for a second digitalWrite(13, LOW); // set the LED off sleep(1000); // wait for a second } </code></pre> <p>I was able to locate <code>sleep.h</code>:</p> <pre><code>$ locate sleep.h | grep avr /usr/lib/avr/include/avr/sleep.h </code></pre> <p>So then I started reading <code>avr/sleep.h</code>, and it seems like I'm doing it right, according to the examples. So, why might this be failing?</p>
<p>"sleep()" is not a function on arduino. The sleep.h file contains functions for the hardware sleep functionality used to reduce power consumption when processing isn't necessary. "delay()" is the right thing to use.</p> <p>AVR only has one thread, and so there is no meaning to pausing execution by deferring to another thread. Hardware interrupts will always interrupt the current code no matter what it is doing, they are not equivalent to threads (although they can introduce similar bugs). </p> <p>If you want to wait and still do other calculations you will need to write code that can wait for a time without blocking. This can be done many ways, one way being to use the arduino library function "millis()" to repeatedly check if it is time to do a certain action, and doing something else for a while if not.</p> <p>Also, vanilla arduino should be using its own packaged avr lib, for example:</p> <pre><code>arduino/hardware/tools/avr/avr/include/avr/sleep.h </code></pre> <p>instead of the one located in your usr/lib directory. </p>
4705
|bluetooth|
Sending multiple channels with bluetooth
2014-10-24T12:05:19.787
<p>I have ordered my HC-05 BT modules. My question is this: Is it possible to send multiple channels over bluetooth. For example, stereo sound has two channels. I think i have seen people do this but i'm not sure.</p> <p>If it is possible, could you please provide some more information on how its done? Thanks!</p>
<p>To add to BrettM answer, Bluetooth is the <em>RF</em> standard on which many protocols can <em>stack up</em>; each such protocol is called a 'Bluetooth Profile'.</p> <p>The Bluetooth model you purchased comes only with the <a href="http://en.wikipedia.org/wiki/List_of_Bluetooth_profiles#Serial_Port_Profile_.28SPP.29" rel="nofollow">Serial Port Profile</a> (<strong>SPP</strong>) profile implemented in the firmware. This mean that you can use it for establishing serial communication.</p> <p>As serial protocol will probably be too slow for stereo Audio over Bluetooth, Audio usually use a different profile called <a href="http://en.wikipedia.org/wiki/List_of_Bluetooth_profiles#Advanced_Audio_Distribution_Profile_.28A2DP.29" rel="nofollow">Advanced Audio Distribution Profile</a> (<strong>A2DP</strong>). Unfortunately, the HC-05 does not come with this protocol stack implemented in its firmware. If your primary goal is to send stereo Audio over Bluetooth, consider purchasing a dedicated chip, such as <strong>XS3868</strong> or Sparkfun's <strong>RN-52</strong>. For beginners, it is recommended to get one with a breakout board for easy integration with Arduino projects.</p> <p>For completeness, there are many other Bluetooth profiles, each is optimized for different task. See Wikipedia for the full list: <a href="http://en.wikipedia.org/wiki/List_of_Bluetooth_profiles" rel="nofollow">http://en.wikipedia.org/wiki/List_of_Bluetooth_profiles</a></p>
4709
|usb|
Get board.vid and board.pid value in code
2014-10-24T20:58:24.140
<p>I'm working on a custom Arduino core based on the teensy code and want to be able to get the board USB VID/PID from boards.txt, as in .board.vid and .board.pid</p> <p>From what I can tell, Arduino already does this for the Leonardo and similar since if I change the VID/PID in boards.txt then the sketch will run with those values.</p> <p>But how do I actually get at them? Right now the code I have has hard coded values, but it would be great to make them dynamic.</p>
<p>The preprocessor will sub in the values for the names "USB_PID" and "USB_VID"</p> <p>this line in "platform.txt" grabs them and makes build flags for them: </p> <pre><code>build.usb_flags=-DUSB_VID={build.vid} -DUSB_PID={build.pid} '-DUSB_MANUFACTURER={build.usb_manufacturer}' '-DUSB_PRODUCT={build.usb_product}' </code></pre> <p>the -D* option in the build is equivalent to the following lines being in the code</p> <pre><code>#define USB_VID /*value of build.vid*/ #define USB_PID /*value of build.pid*/ #define USB_MANUFACTURER /*value of build.usb_manufacturer*/ #define USB_PRODUCT /*value of build.usb_product*/ </code></pre> <p>If you are curious, they are used by the libraries in "USBCore.cpp". Also, they will never be defined for devices they don't apply to.</p>
4721
|arduino-uno|lcd|
20x4 LCD shows alternating blank lines
2014-10-25T17:38:31.057
<p>I just acquired a Arduino learning kit, which includes a 20x4 LCD display. I was going to test it, so I grabbed an example "hello world" program from the Arduino docs, connected the display appropriately, and then "Voila! ... Oh, it didn't work.".</p> <p>The display lights up both its backlight and characters, however not in any desirable pattern. The first and third lines are full white (display is white-on-blue), while lines 2 and 4 are full blue. See picture:</p> <p><img src="https://i.stack.imgur.com/4PyVc.jpg" alt="lines: white blue white blue"></p> <p>The below schematic is exactly how I've connected the display, which should be correct.</p> <p><img src="https://i.stack.imgur.com/kWKVx.png" alt="schematic"></p> <p><sup><a href="/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fkWKVx.png">simulate this circuit</a> &ndash; Schematic created using <a href="https://www.circuitlab.com/" rel="nofollow">CircuitLab</a></sup></p> <p>I triple-checked all wiring for any shorts, adjusted the potentiometer to a good value and quadruple-checked the connections, and wasn't able to find any errors.</p> <p>The dead-simple example program is following:</p> <pre><code>#include &lt;LiquidCrystal.h&gt; // LiquidCrystal display with: // rs on pin 12 // rw on pin 11 // enable on pin 10 // d4, d5, d6, d7 on pins 5, 4, 3, 2 LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 2); void setup() { // Print a message to the LCD. lcd.begin(20, 4); lcd.print("hello, world!"); } void loop() { } </code></pre>
<p>Just putting the jumper wires in the plated holes, doesn't always give a good connection. Try applying some lateral force, to make sure all of them have proper contact. Wiring looks otherwise fine. </p> <p>A more permanent solution would be to solder some male headers to the display, so you can properly seat it into the breadboard.</p>
4725
|arduino-uno|button|resistor|
Performance of internal vs external resistors
2014-10-26T01:36:55.833
<p>Is there any significant performance trade-off between buttons wired with the internal vs external pull-up/down resistors? I see a lot of tutorials demonstrating the use of external resistors when wiring a simple button, like <a href="http://www.arduino.cc/en/Tutorial/Pushbutton">this</a> and <a href="http://arduino.cc/en/tutorial/button">this</a>. But since the Arduino/AVR includes internal pull-up resistors, you can wire a button without any external resistor as demonstrated <a href="http://arduino.cc/en/Tutorial/InputPullupSerial">here</a>.</p> <p>Is there any good reason to complicate your design with an extra resistor?</p>
<p>If you are using the pin as an input in close proximity to the Arduino there is little reason to use an external pullup.</p> <p>There are a number of factors to consider.</p> <p>If the switch is some distance from the chip and/or in a noisy environment it will be more susceptible to interference as the internal pullups are high impedance (20kΩ to 150kΩ depending on model).</p> <p>If the pin is used as both input &amp; output the pullup can reduce the voltage swing.</p> <p>In other applications e.g. Raspberry Pi the state of the pin between boot and software initialisation can be significant, but this should not be an issue with Arduino.</p>
4728
|build|
Compiling includes with Ino
2014-10-26T04:20:21.693
<p>I'm attempting to compile this simple <a href="https://github.com/thomasfredericks/Bounce-Arduino-Wiring/blob/master/Bounce2/examples/bounce/bounce.ino" rel="nofollow">bounce.ino</a> example with the <a href="http://inotool.org/" rel="nofollow">ino</a> tool, but it's giving me the error:</p> <pre><code>Bounce2.h: No such file or directory </code></pre> <p>I've placed it in the same directory as bounce.ino. Why can't it find the header?</p> <p>Edit: I'm using Ubuntu.</p>
<p>What OS are you using?</p> <p>If you're in Linux (and some OS X installations) you should note that bounce.h and Bounce.h are two completely different files - you need to make sure you have the capitalization the same in your #include directive as the actual file on disk is.</p>
4736
|wires|
Common Wire sizes for connecting peripherals to arduino
2014-10-26T15:04:10.003
<p>Please don't judge me for asking this question i have never touch arduino before but We plan to use it in our thesis we are doing a budget plan and it must include wires. can anyone tell me the common wire sizes used? This is to estimate the prices.</p>
<p>Depends what you’re doing.</p> <p>For low power (&lt; 12v, 500mA) peripherals and digital signals:</p> <p>If you’re going to use breadboard (and you really should start with breadboard) you’ll need solid core hook up wire. You can find pre-cut, pre-stripped sets with a variety of lengths and colours if you’re looking for neatness and simplicity. (An example can be found at: <a href="http://www.maplin.co.uk/p/jump-wire-kit-fs65v" rel="nofollow">http://www.maplin.co.uk/p/jump-wire-kit-fs65v</a>) Usually it’s 22AWG wire, so you could get a reel and cut it yourself if you’re going to need a lot or are going to solder it in place.</p> <p>After you’re done breadboarding and want to make something more permanent you should look at rainbow cable. You can tear it to get anything from 2 to 32 way cables, and it’s almost impossible to get the wrong way around. You can solder it directly to a PCB or crimp connectors onto the ends for more flexibility. (You can find this stuff everywhere, but Sparkfun is always there if you can’t: <a href="https://www.sparkfun.com/products/10649" rel="nofollow">https://www.sparkfun.com/products/10649</a>)</p> <p>For higher power (> 12v, 1A): </p> <p>Keep it away from the Arduino! Use switching transistors, relays, or MOSFETs and use cabling that meets, or preferably exceeds, the power that you’re going to put through it.</p> <p>I don’t know where you’re going to buy this, but in the UK I use Mouser, Farnell, and RS for most of my electronics supplies. Never buy cabling off Ebay, a lot of it is counterfeit and won’t meet the claimed spec.</p> <p>Hope this helps.</p>
4740
|avrdude|oscillator-clock|
Flashing a ATmega328 that came from an Arduino to not use an external oscillator
2014-10-27T05:09:00.110
<p>I have a ATmega328p chip from a kit that was supposed to be an Arduino compatible thing. I decided to go beyond Arduino and try to program the chip directly. I setup an UNO as an Arduino ISP, more or less like the image here, but added some LEDs to pins 8, 9 and 10 for feedback.</p> <p><img src="https://i.stack.imgur.com/Dvyjj.png" alt="Arduino ISP"></p> <p>This image has this caption.</p> <blockquote> <p>Because no external clock source is connected, the ATmega must be configured to use its internal clock.</p> </blockquote> <p>I think this chip was flashed with whatever tells it to use an external oscillator. And I do not have an external oscillator. </p> <p>So how can I tell the chip to again use an internal oscillator when using an UNO as my programmer?</p> <pre><code>» avrdude -p m328p -c avrisp -b 19200 -P /dev/cu.usbmodem1d11121 avrdude: AVR device initialized and ready to accept instructions Reading | ################################################## | 100% 0.05s avrdude: Device signature = 0x000000 avrdude: Yikes! Invalid device signature. Double check connections and try again, or use -F to override this check. avrdude done. Thank you. </code></pre> <p>I assume a device id of zero means the chip is not responding with data? because it's core is not cycling?</p> <p>Do I need an oscillator installed just so I can wake it it up and tell it to not use an oscillator?</p>
<p>Even though an answer has been accepted, I just want to add for future viewers that you can google for arduino breadboard internal oscillator and get the text to copy into the boards.txt file. That will allow you to use the Arduino IDE to burn the fuses. You will be able to find versions to run at both 8mhz and 1mhz.</p> <p>Also, if you have an extra Uno laying around, you could always pop the chip in there and reset the fuses, then take it out and use it on a breadboard.</p>
4762
|programming|c++|data-type|
How to convert byte array to float
2014-10-28T16:35:52.973
<p>How can I convert a byte array to float? </p> <p>Code:</p> <pre><code>void send_data() { CCPACKET data; data.length=2; float lon=26.533255; float lat=27.533463; data.data[0]=lon; data.data[1]=lat; if(cc1101.sendData(data)){ Serial.println(data.data[0]); Serial.println(data.data[1]); Serial.println(" sent ok "); return true; }else{ Serial.println("sent failed "); return false; } } </code></pre> <p>The problem is when I print those two variables it just prints lon 26.00 and lat 27.00 but not lon 26.533255 lat 27.533463 as I expected.</p> <p>Here is the header file for CCPACKET I use:</p> <pre><code>#ifndef _CCPACKET_H #define _CCPACKET_H #include "Arduino.h" /** * Buffer and data lengths */ #define CC1101_BUFFER_LEN 64 #define CC1101_DATA_LEN CC1101_BUFFER_LEN - 3 /** * Class: CCPACKET * * Description: * CC1101 data packet class */ class CCPACKET { public: /** * Data length */ byte length; /** * Data buffer */ byte data[CC1101_DATA_LEN]; /** * CRC OK flag */ boolean crc_ok; /** * Received Strength Signal Indication */ byte rssi; /** * Link Quality Index */ byte lqi; }; #endif </code></pre> <p>I was trying to fix it by this part of code, but without success:</p> <pre><code>float lon=26.533543; *((float *)data.data[0]) = lon; </code></pre> <p>Can someone help me to convert the byte array to float?</p>
<p>You can choose to treat the byte array as a float array by typecasting. Your attempt isn't far from a solution:</p> <pre><code>((float *)data.data)[0] = lon; // uses data.data[0] ... data.data[3] ((float *)data.data)[1] = lat; // uses data.data[4] ... data.data[7] </code></pre> <p>When printing you should also treat the data array as float array:</p> <pre><code>Serial.println(((float *)data.data)[0]); </code></pre> <p>It looks like you are sending the data over some interface. Then of course you need to typecast the binary data back into a float at the receiving end (if you want to do something useful with it) - similar to what is done above when it is passed to Serial.println.</p>
4767
|sensors|power|voltage-level|resistor|electronics|
What does the datasheet information for a switch mean?
2014-10-29T17:10:39.230
<p>I'm clueless when it comes to the information on datasheets for switches. When I see a datasheet for LEDs or servos, I'm used to seeing a fairly straightforward call out for the required volts and amps. </p> <p>A project I'm working on now requires turning on an LED using a float switch like this one: <a href="http://www.seeedstudio.com/depot/water-level-switch-p-565.html" rel="nofollow">Water Level Switch</a></p> <p>The max switching voltage and current values, and minimum voltage info is really throwing me. The minimum voltage, for instance, is 250v DC! Does a $5 switch really require 250 volts? I haven't been able to find many schematics where they are just using a switch like this without a pump or other hardware, but I seem to remember seeing someone run a switch like this with 5v pin. And I'm totally unsure what the current would be/if I need a resistor, etc.</p>
<p>It says "<em>maximum</em> breakdown voltage: 250 V DC". That's maximum, not minimum. Above 250 V DC the arc which is created by an opening contact isn't guaranteed to extinguish. It's defined for DC voltage because then the arc remains; for AC the arc will extinguish automatically when the current crosses zero.</p>
4769
|arduino-uno|serial|uploading|usb|
Can I simply unplug the Arduino usb if serial communication is active?
2014-10-29T17:36:16.210
<p>So, after the sketch is uploaded, and I want to turn the Arduino off while it is running a sketch, all I have to do is unplug it. Should be safe as long as nothing is uploading. But I wonder, if I use serial communication between the Arduino and my Computer in a sketch, does it harm either if I simply unplug it?</p>
<p>Yes, you can unplug it directly whether if serial communication is active or not if you dont need power supply anu more using usb cable</p>
4773
|arduino-uno|wifi|shields|
Breakout vs Shield
2014-10-29T21:47:24.337
<p>I would like to extend my arduino uno with WIFI and I am checking different options.</p> <p>These are:</p> <p><a href="http://www.exp-tech.de/Shields/Wireless/WiFi/Adafruit-CC3000-Breakout-with-Onboard-Ceramic-Antenna.html" rel="nofollow">Adafruit-CC3000-Breakout-with-Onboard-Ceramic-Antenna</a></p> <p><a href="http://www.exp-tech.de/Shields/Arduino-WiFi-Shield-integrierte-Antenne.html" rel="nofollow">Arduino WiFi Shield (integrierte Antenne)</a></p> <p>Viewing the price, obviously I understand that the shield will have more functions, I think also it is more "friendly" for programming and the breakout requires more low level code(I am not afraid of it...)</p> <p>I already have an arduino yun but it is busy with a project, so I need something for the uno.</p> <p>For what kind of projects could be better each of them? and what are the main differences between a shield and a breakout?</p> <p>Also in the future I would do some projects with gsm, so this question could be similar ... gsm shield vs breakout.</p>
<p>A breakout board usually has the sole purpose of making a single chip (gross generalization here...) available to the experimenter by "breaking out" its signal lines on to dedicated pins - header pins, for instance. It is only large enough for the chip and the printed circuit wiring to do this, and seldom adds any function beyond what the chip itself provides.</p> <p>A "shield" is a larger board that usually plugs directly onto an Arduino board, matches its form factor, and is built for a dedicated more complex function, like a complete GPS system or cellular communication system (although some shields are left mostly blank to provide you the space to build your own device). They probably have several chips engineered and built into a complete plug-and-go sub-system.</p> <p>One is to learn to use a chip or other device without having to solder up your own board, especially with surface mount devices. The other is a ready-to-go system building block.</p>
4774
|arduino-uno|serial|led|shields|
How to pass rx/tx led outputs to a shield
2014-10-29T21:56:17.313
<p>I have an Arduino Uno. I am building a custom shield and was wondering how I would connect two of the LEDs on the shield to the TX / RX LEDs on the Uno. Digital pins 0 and 1 seem obvious, but after further research, it appears that they are not for this.</p> <p>In better terms, I want two LEDs on my shield that replicate the TX / Rx LEDs on the Arduino Uno.</p> <p>How would I do this?</p>
<p>If you need just indicate data on TX/RX you can make simple circuit on shield bound to TX/RX lines.</p> <p><img src="https://i.stack.imgur.com/EhMRw.png" alt="enter image description here"></p>
4782
|programming|variables|
Help with a function that accepts different parameter types
2014-10-30T02:06:45.260
<p>I'm trying to create a function that prints out an XML tag with a value. I have the code below, but kind of stuck. I'd like to be able to call the function, and pass a value that could be a float, int, string or char. Appreciate any help.</p> <pre><code>char PingTime[6] = "3ms"; char PingText[60] = "ping reply blah blah"; float humidity = "40.56"; int DigialPin = 0; PrintXMLTag(cl,"pingtime",PingTime); PrintXMLTag(cl,"PingText",PingText); PrintXMLTag(cl,"humidity",humidity); PrintXMLTag(cl,"DigialPin",DigialPin); void PrintXMLTag_DEC(EthernetClient cl, const char* tag, NotSure?? val) { char tmp [100]; StrClear(tmp,100); // If val type is float ---------------------- int d1 = val; // Get the integer part float f2 = val - d1; // Get fractional part int d2 = trunc(f2 * 10000);// Turn into integer sprintf(tmp,"&lt;%s&gt;%d.%02d&lt;/%s&gt;\n",tag,d1,d2,tag); // end float // If val type is string ---------------------- // If val type is int ---------------------- // If val type is char ---------------------- cl.print(tmp); } </code></pre> <hr> <p>Update, now converting the type to char before calling the PrintXML function resolves my initial issue. If I use the code below it seems to chew up a lot of memory, is there something obviously wrong? As a workaround I'm just printing the XML tags using cl.print and the memory usage is stable.</p> <pre><code>void PrintXMLTag(EthernetClient cl, char* tag, char* val) { char tmp [100]; sprintf(tmp,"&lt;%s&gt;%s&lt;/%s&gt;\n",tag,val,tag); cl.print(tmp); StrClear(tmp,100); } </code></pre>
<p>try using this example instead of iostream you can use iostream.h too..</p> <pre><code>#include &lt;iostream&gt; using namespace std; int sum (int a, int b) { return a+b; } double sum (double a, double b) { return a+b; } int main () { cout &lt;&lt; sum (10,20) &lt;&lt; '\n'; cout &lt;&lt; sum (1.0,1.5) &lt;&lt; '\n'; return 0; } </code></pre>
4790
|led|resistor|
Which side should I connect the resistor on?
2014-10-30T11:07:18.453
<p>I understand that when connecting an LED and a resistor in series; the resistor can be placed on any side of the LED as the current will remain same in a series connection. Please correct me if I'm wrong, but I was under the impression that conventionally the electrons flow from positive to negative. So shouldn't the resistor be placed before an LED to limit the flow of charge. </p> <p>In this scenario the negative is connected ground and the positive to a power source. So I don't understand the chain Link analogy as well. Where the whole chain moves as a whole because here the flow ends with the GND right ?</p>
<p>Another way to look at it is this:<br>Imagine the current flowing through the LED toward the resistor to be greater than the current flowing out of the resistor toward ground. The only way this could happen is if some of the charge - the difference due to the different currents - accumulated in the resistor. But that cannot happen forever, and not even for any appreciable length of time. (If it could, and did, the device would eventually fail - spectacularly!) So, because charge in must equal charge out over time (and over a very short period, at that) current in has to equal current out.</p>
4792
|string|
sprintf trouble
2014-10-30T11:56:37.283
<pre><code>char cTime[22]; sprintf(cTime, "%04s/%02s/%2s:%02s:%02s:%02s", year(), month(), day(), hour(), minute(), second()); </code></pre> <p>This <code>sprintf</code> line causes this error:**B0100000063f694Š</p> <p>Could someone help me debug this? Thank you.</p>
<p>Yes - try making each of the %-specifiers match the kind of conversion you want for each variable in the rest of the call. F/ex, %d converts an integer to a string in decimal radix, %f converts a double to a number with a decimal fraction, etc. In all cases, the output will be as characters; you don't need to specify that.</p>
4795
|arduino-uno|sensors|library|timers|
TCS3200 color sensor not reading with delay lower then 4000 ms using TimerOne.h
2014-10-30T14:10:54.587
<p>I'm trying to get the color sensor TCS3200 to give color values with a delay lower than 4000 ms. I've found a library to interface the TCS3200 from this <a href="http://www.elecfreaks.com/5521.html" rel="nofollow">link</a>. </p> <p>I've modified the code to serve my needs and its works fine, almost! The before mentioned library uses <a href="http://playground.arduino.cc/Code/Timer1" rel="nofollow">TimerOne.h</a>, which can not accept a delay lower than 4000 ms. </p> <p>My question is therefor, if it is somehow possible to modify my code, so I can lower the delay?</p> <p>This is my code:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;TimerOne.h&gt; #define S0 6 #define S1 5 #define S2 4 #define S3 3 #define OUT 2 int g_count = 0; // count the frequecy int g_array[3]; // store the RGB value int g_flag = 0; // filter of RGB queue float g_SF[3]; // save the RGB Scale factor // Init TSC230 and setting Frequency. void TSC_Init() { pinMode(S0, OUTPUT); pinMode(S1, OUTPUT); pinMode(S2, OUTPUT); pinMode(S3, OUTPUT); pinMode(OUT, INPUT); digitalWrite(S0, LOW); // OUTPUT FREQUENCY SCALING 2% digitalWrite(S1, HIGH); } // Select the filter color void TSC_FilterColor(int Level01, int Level02) { if(Level01 != 0) Level01 = HIGH; if(Level02 != 0) Level02 = HIGH; digitalWrite(S2, Level01); digitalWrite(S3, Level02); } void TSC_Count() { g_count ++ ; } void TSC_Callback() { switch(g_flag) { case 0: TSC_WB(LOW, LOW); //Filter without Red break; case 1: g_array[0] = g_count; TSC_WB(HIGH, HIGH); //Filter without Green break; case 2: g_array[1] = g_count; TSC_WB(LOW, HIGH); //Filter without Blue break; case 3: g_array[2] = g_count; TSC_WB(HIGH, LOW); //Clear(no filter) break; default: g_count = 0; break; } } void TSC_WB(int Level0, int Level1) //White Balance { g_count = 0; g_flag ++; TSC_FilterColor(Level0, Level1); Timer1.setPeriod(1000000); // set 1s period } void setup() { TSC_Init(); Serial.begin(115200); Timer1.initialize(); // defaulte is 1s Timer1.attachInterrupt(TSC_Callback); attachInterrupt(0, TSC_Count, RISING); delay(4000); for(int i=0; i&lt;3; i++) Serial.println(g_array[i]); g_SF[0] = 255.0/ g_array[0]; //R Scale factor g_SF[1] = 255.0/ g_array[1] ; //G Scale factor g_SF[2] = 255.0/ g_array[2] ; //B Scale factor Serial.println(g_SF[0]); Serial.println(g_SF[1]); Serial.println(g_SF[2]); } void loop() { g_flag = 0; int R = int(g_array[0] * g_SF[0]); int G = int(g_array[1] * g_SF[1]); int B = int(g_array[2] * g_SF[2]); if((R&gt;245) &amp;&amp; (R&lt;265) &amp;&amp; (G&gt;245) &amp;&amp; (G&lt;265) &amp;&amp; (B&gt;245) &amp;&amp; (B&lt;265)) // White { Serial.println("Color is white"); }else if((R&gt;24) &amp;&amp; (R&lt;44) &amp;&amp; (G&gt;56) &amp;&amp; (G&lt;76) &amp;&amp; (B&gt;95) &amp;&amp; (B&lt;115)) // Blue { Serial.println("Color is blue"); }else if((R&gt;56) &amp;&amp; (R&lt;76) &amp;&amp; (G&gt;107) &amp;&amp; (G&lt;127) &amp;&amp; (B&gt;80) &amp;&amp; (B&lt;100)) // Green { Serial.println("Color is green"); }else if((R&gt;171) &amp;&amp; (R&lt;191) &amp;&amp; (G&gt;154) &amp;&amp; (G&lt;174) &amp;&amp; (B&gt;71) &amp;&amp; (B&lt;91)) // Yellow { Serial.println("Color is yellow"); }else if((R&gt;77) &amp;&amp; (R&lt;97) &amp;&amp; (G&gt;46) &amp;&amp; (G&lt;66) &amp;&amp; (B&gt;43) &amp;&amp; (B&lt;63)) // Brown { Serial.println("Color is brown"); }else if((R&gt;39) &amp;&amp; (R&lt;59) &amp;&amp; (G&gt;38) &amp;&amp; (G&lt;58) &amp;&amp; (B&gt;36) &amp;&amp; (B&lt;56)) // Brown dark { Serial.println("Color is brown dark"); }else if((R&gt;20) &amp;&amp; (R&lt;40) &amp;&amp; (G&gt;43) &amp;&amp; (G&lt;63) &amp;&amp; (B&gt;48) &amp;&amp; (B&lt;68)) // Turkis { Serial.println("Color is turkis"); }else if((R&gt;39) &amp;&amp; (R&lt;59) &amp;&amp; (G&gt;77) &amp;&amp; (G&lt;97) &amp;&amp; (B&gt;55) &amp;&amp; (B&lt;75)) // Green { Serial.println("Color is green"); }else { Serial.print("Red = "); Serial.println(R); Serial.print("Green = "); Serial.println(G); Serial.print("Blue = "); Serial.println(B); }; delay(4000); } </code></pre> <p>I've searched all over the net and didn't find any good solutions, where I can still specify the colours by hex degree. </p> <p>All help would be highly appreciated! </p>
<p>You can increase the frequency (x10) by setting S0 HIGH and S1 LOW. Then you can change the timerone frequency from once a second to once every 100ms (Timer1.setPeriod(100000);). Then you can change your delay to delay(400). </p> <p>PS I think you only need to wait for a bit over 3 timerone cycles, so delay(350) should also work.</p>
4801
|arduino-uno|rotary-encoder|
Rotary encoder on Uno and interrupts issue
2014-10-30T16:20:56.883
<p>This question is regarding a project using an Arduino Uno.</p> <p>I have one of these <a href="http://www.sparkfun.com/products/11102" rel="nofollow">quadrature rotary encoders</a>.</p> <p>I'm using a slightly modified version of the code from the article, <a href="http://www.hessmer.org/blog/2011/01/30/quadrature-encoder-too-fast-for-arduino" rel="nofollow">Quadrature Encoder too Fast for Arduino (with Solution)</a>, which uses a library called <a href="http://code.google.com/p/digitalwritefast/" rel="nofollow">digitalwritefast</a>.</p> <p>My version of the code on <a href="http://pastebin.com/ts1QzbgM" rel="nofollow">pastebin</a> - I modified to use different pins for the Uno and a single encoder:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;digitalWriteFast.h&gt; // library for high performance reads and writes by jrraines #define c_LeftEncoderInterrupt 0 #define c_LeftEncoderPinA 2 #define c_LeftEncoderPinB 3 volatile bool _LeftEncoderBSet; volatile long _LeftEncoderTicks = 0; void setup() { Serial.begin(115200); pinMode(c_LeftEncoderPinA, INPUT); digitalWrite(c_LeftEncoderPinA, LOW); pinMode(c_LeftEncoderPinB, INPUT); digitalWrite(c_LeftEncoderPinB, LOW); attachInterrupt(c_LeftEncoderInterrupt, HandleLeftMotorInterruptA, RISING); } // Interrupt service routines for the left motor's quadrature encoder void HandleLeftMotorInterruptA() { _LeftEncoderBSet = digitalReadFast2(c_LeftEncoderPinB); // read the input pin _LeftEncoderTicks -= _LeftEncoderBSet ? -1 : +1; } void loop() { Serial.print(_LeftEncoderTicks); Serial.print("\n"); delay(20); } </code></pre> <p>I am attaching output A of the encoder to pin 2 and output B to pin 3.</p> <p>This setup works fine and I can detect turns in both directions, but my problem is, if I set pin B to any other pin, I get positive direction only (regardless of the direction in which the encoder is turned) - as if pin B isn't plugged in at all (I am modifying <code>c_LeftEncoderPinB</code> accordingly).</p> <p>I'm assuming that this is something to do with pin 3 being the only other interrupt pin on the Uno (I can't see anything else unique about that pin). Yet I don't know why because the interrupt is on pin A (we're reading the value of pin B in that interrupt, though).</p>
<p>OK embarrassingly it turns out my wiring was wrong! I was going astray as it was working in both directions as described, even when only one of the outputs was connected, as long output B was connected to an interrupt. Once the wiring was sorted everything worked perfectly, in both directions, using just one of the interrupt ports.</p>
4805
|bootloader|atmega328|isp|icsp|
Homebrew Arduino using ATMEGA328P, ISP or ICSP?
2014-10-30T18:20:46.217
<p>I plan on creating a homebrew Arduino breakout board using the ATMEGA328P smd version. I'm geeting confused by the wealth of information out there as to whether I should be using ICSP or ISP to program it. It is a blank chip, aka no Arduino bootloader on it yet. I'd rather not have to buy a specialized programmer to burn the bootloader, I do have another Arduino I could use to burn the bootloader and upload sketches to it with. </p> <p>So the question is; Do I use ISP or ICSP, or both?</p>
<p>To program it you could use an ISP programmer. In which case you would not need the bootloader. You can <a href="https://www.arduino.cc/en/Tutorial/ArduinoISP" rel="nofollow noreferrer">use an Arduino as an ISP programmer</a>, but that's not really a long term solution, as you can no longer use the arduino for anything else.</p> <p>The other option is to program it using a usb-to-serial. In this case you do need the arduino bootloader. To program this bootloader (once) you can use the above method, using an arduino board.</p> <p>Third option would be implement USB into the bootloader, just like the <em>completely Open Source</em> Pro Trinket (<a href="https://github.com/adafruit/Adafruit_ProTrinket_Bootloader" rel="nofollow noreferrer">bootloader</a> and <a href="https://learn.adafruit.com/system/assets/assets/000/018/948/large1024/adafruit_products_protrink5vschm.png?1408558753" rel="nofollow noreferrer">schematic</a>). You'd have to add some resistors, zener diodes and a usb plug (just strip an old usb cable). A bit more technical and challenging, but definitely the cheapest</p>
4817
|led|sketch|button|debounce|
Unintended reaction: Sketch makes LEDs turn on and of randomly/LEDs don't react
2014-10-31T02:40:07.877
<p>Update: This piece of code does not do the same as the one in the right answer, it also reacts when one lets go of the button.</p> <pre><code>int button_prev = 0; int button = 0; void loop(){ button_prev = button; button = digitalRead(12); if (button_prev != button) { digitalWrite(act_pin[j], HIGH); j = (j+1) % 5; } } </code></pre> <p>I printed out j and it seems like, instead of counting up +1 everytime the button is pressed once, it turns +1 and then +1 again which makes two LEDs at a time turn on. But I don't see where the behavior of j comes from...</p> <p>[Update: There was a mistake in the code which caused the random behavior, but now, nothing happens when I push the button.]</p> <p>[I wrote a sketch which is supposed to make the Arduino turn one of five LEDs on one after another every time I press the switch.</p> <p>But instead of turning one LED on after another, directly after upload it just makes them turn on and of at random. I don't push the button. <code>Serial.println</code> as well just spits out one character, similiar looking to a <code>d</code>.]</p> <p>Can anyone point out my mistake to me?</p> <p>This is the circuit</p> <p><img src="https://i.stack.imgur.com/ohDRc.jpg" alt="enter image description here"></p> <p>and this is the <em>old code</em> of the sketch</p> <pre><code>int act_pin[6] = {A0, A1, A2, A3, A4}; int j = 0; void setup(){ Serial.begin(9600); for (int k = 0; k &lt; 5; k++) { pinMode(act_pin[k], OUTPUT); //sets analog pins A0 - A4 as output digitalWrite(act_pin[k], LOW); //turns LEDs connected to A0 - A4 off pinMode(12, INPUT); //sets pin connected to button as input } } void loop(){ char button = {digitalRead(12)}; //stores if the button was pressed Serial.println(button); if(button == HIGH){ digitalWrite(act_pin[j], HIGH); //turns LEDs on A0 - A4 on one after one with every button press j = (j+1) % 5; //makes digitalWrite jump to the next LED next time the button is pressed and limits it to 4 button = LOW; //turns the button's pin low again, so nothing will happen until the button is pressed again } } </code></pre>
<p>I think you're looking for the action (in pseudo-code):</p> <pre><code>ONCE (Button Pressed): Light LED j; j++ </code></pre> <p>But you have an IF(button) in a Loop{}. Something like:</p> <pre><code>WHILE (Button Pressed): Light LED j; j++ </code></pre> <p>So when you press the button j will increment every iteration of Loop {} (very fast) and you won't be able to see the LEDs changing. Your 'button = LOW' is not effective because 'button' gets set again the next time if the button is still pressed.</p> <p>Try printing j instead of button at the line:</p> <pre><code>Serial.println(j); </code></pre> <p>and that should highlight the problem.</p> <p>I would implement a ONCE(Button Pressed) function by observing the previous button state and checking it has changed from LOW to HIGH.</p> <pre><code> button_prev = button; button = digitalRead(12); // Check if button changed from LOW to HIGH if (!button_prev &amp;&amp; button) { ...code } </code></pre> <p>EDIT: Dealing with Contact Bounce</p> <p>Switches are mechanical so they don't switch cleanly. This is called contact bounce and means the switch switches on/off very rapidly for about 10ms or so after the contact has been pressed or released.</p> <p>See <a href="http://www.picotech.com/experiments/switch_bounce/measuring-switch-bounce.html" rel="nofollow noreferrer">Measuring Switch Bounce</a></p> <p><img src="https://i.stack.imgur.com/I0Zol.gif" alt="enter image description here"></p> <p>You can deal with it quite simply in the code as follows (pseudo code) just by waiting for the bounce to dissapear and checking the button is still pressed:</p> <pre><code>ONCE (Button Pressed): WAIT(20ms) // wait for the bounce to stop IF(Button Pressed): // Ensure the button is still pressed ...code... </code></pre> <p>Try the following Arduino Code:</p> <pre><code> button_prev = button; button = digitalRead(12); // Check if button changed from LOW to HIGH if (!button_prev &amp;&amp; button) { delay(20); // Wait for debounce if(digitalRead(12)) { // Make sure the button is still pressed ...code } } </code></pre>
4837
|lcd|arduino-duemilanove|
How to display tilt sensor data on an LCD?
2014-11-02T20:14:26.260
<p>I'd like for a 16x2 LCD monitor from <a href="https://www.sparkfun.com/products/9394" rel="nofollow">Sparkfun</a> to display sensor data from a 4-directional tilt sensor from <a href="http://learn.parallax.com/KickStart/28036" rel="nofollow">Parallax</a>. The Arduino board is a Duemillanove. The board will run and power both programs and modules, but the serial monitor displaying the tilt sensor data will not relay the info to the LCD display. Any suggestions?</p> <p>Here are the two pieces of code I am trying to get to work together—they are both from Arduino:</p> <p>For the tilt:</p> <pre><code>void setup() { Serial.begin(9600); } void loop() { Serial.print("Photo 1: "); Serial.print(digitalRead(6), DEC); // Display Out 1 value Serial.print("; "); Serial.print("Photo 2: "); Serial.println(digitalRead(7), DEC); // Display Out 2 value delay(250); // Wiat 1/4 second } </code></pre> <p>For the LCD:</p> <pre><code>#include &lt;SoftwareSerial.h&gt; // Attach the serial display's RX line to digital pin 2 SoftwareSerial mySerial(3,2); // pin 2 = TX, pin 3 = RX (unused) void setup() { mySerial.begin(9600); // set up serial port for 9600 baud delay(500); // wait for display to boot up } void loop() { mySerial.write(254); // move cursor to beginning of first line mySerial.write(128); mySerial.write(" "); // clear display mySerial.write(" "); mySerial.write(254); // move cursor to beginning of first line mySerial.write(128); mySerial.write("movement recorded"); while(1); // wait forever } </code></pre> <p>Update:</p> <p>I'm still tinkering with the suggested program from @Ariser shown below, but keep getting a compile error:</p> <p>tilt_lcd_ase.cpp: In function ‘void loop()’:<br> tilt_lcd_ase.cpp:24:43: error: expected ‘)’ before ‘;’ token<br> tilt_lcd_ase.cpp:25:43: error: expected ‘)’ before ‘;’ token </p> <p>I've done some research and one person had a similar problem, but it was within #include not void loop. The search continues, but if anyone has a suggestion please chime in. The liquid crystal library is also turning up similar errors but it needs a closer look. </p>
<p>by the looks of it you need to close the brackets of the <em>sprintf()</em> statement shown below if you had copied the code from Ariser: </p> <pre><code>sprintf(gl_senstr1, "%d", digitalRead(6); sprintf(gl_senstr2, "%d", digitalRead(7); </code></pre> <p>replace it with:</p> <pre><code>sprintf(gl_senstr1, "%d", digitalRead(6)); sprintf(gl_senstr2, "%d", digitalRead(7)); </code></pre> <p>That is the error you are seeing because of <em>sprintf()</em> not seeing a close to its statement ;) </p>
4843
|programming|led|button|
Led on when not supposed to be
2014-11-03T06:51:30.383
<p>So I made a program that controls two LED's when two buttons are pressed, but one of the LED's comes on when the button isn't pressed. And what's weird is that if I literally move around the breadboard the LED might turn off for a little, and if hold the button down while doing it the LED remains solid. I have done a lot of taking out and switching wires without any unexpected effects. However, if I switch the LED wires the other LED turns and stays on while the first one turns off, so I am pretty sure that it is a programming error. Here is my code:</p> <pre><code>const int ledPin1 = 8; const int buttonPin1 = 1; const int ledPin2 = 9; const int buttonPin2 = 2; int buttonState1 = 0; int buttonState2 = 0; void setup() { pinMode(ledPin1, OUTPUT); pinMode(buttonPin1, INPUT); pinMode(ledPin2, OUTPUT); pinMode(buttonPin2, INPUT); } void loop() { buttonState1 = digitalRead(buttonPin1); buttonState2 = digitalRead(buttonPin2); if (buttonState1 == LOW) { digitalWrite(ledPin1, HIGH); } else { digitalWrite(ledPin1, LOW); } if (buttonState2 == LOW) { digitalWrite(ledPin2, HIGH); } else { digitalWrite(ledPin2, LOW); } } </code></pre>
<p>The behavior you describe is symptomatic of a floating input.</p> <p>I guess you have directly wired your buttons between input pins and +5V (or GND, that won't change the observed behavior).</p> <p>The problem is when you don't push the button, the input pin is left floating and can be read as HIGH or LOW based on strange factors.</p> <p>The solution to this is to use pullup (if you connect the other side of the button to GND) or pulldown (if your button is connected to +5V) resistors.</p> <p>The following image, off the arduino website, shows such a circuit with a pulldown resistor, i.e. connect the switch to +5V and the resistor to GND:</p> <p><img src="https://arduino.cc/en/uploads/Tutorial/button_schem.png" alt="Pullup resistor example"></p> <p>An even simpler way is to connect the buttons to GND and use <code>pinMode(pin, INPUT_PULLUP);</code> in <code>setup()</code>.</p>
4849
|sensors|interrupt|
Reading a tachogenerator
2014-11-03T10:20:09.437
<p>I'm trying to read a tachogenerator from a washing machine. It outputs an alternating current, with multiple periods per revolution. The voltage for my test case (constant rpm) reads 5.5V. I attached the tachogenerator to Digital 2 and GND and ran this sketch, just to see if a change is detected:</p> <pre><code>int ledPin = 13; volatile int state = LOW; void setup() { pinMode(ledPin, OUTPUT); attachInterrupt(0, blink, RISING); } void loop() { digitalWrite(ledPin, state); delay(500); } void blink() { if (state == LOW) state != state; } </code></pre> <p>Unfortunately, the LED does not light when I start the motor. When I measure the voltage while it is connected to the Arduino, it shows only about 0.7V, which would explain why the LED is not reacting. But why is this?</p>
<p>There's an obvious code problem in your <code>blink()</code> function:</p> <pre><code>state != state; </code></pre> <p>The above statement will never modify your state variable. The <code>!=</code> operator in C/C++ does not perform an assignment (unlike operators such as <code>+=</code> and <code>-=</code>). It's a comparison operator which just tests for inequality. You presumably meant to do this:</p> <pre><code>state = !state; </code></pre> <p>That may not fix your problem entirely though. You might find that the interrupt doesn't get reliably triggered anyway because it's not designed to handle AC. I'd recommend using an external comparator circuit to generate a clean digital signal, such as a Schmitt trigger.</p>
4857
|arduino-uno|programming|led|
How to parse array to x,y positions?
2014-11-03T20:55:07.843
<p>I have 16x16 LED matrix and I want to show some custom characters on it. I saw font made with array like this.</p> <pre><code>const byte zero[16] = { // Create byte array number 0 B0111110, B1111111, B1100011, B1100011, B1100011, B1100011, B1100011, B1100011, B1100011, B1100011, B1100011, B1100011, B1100011, B1100011, B1111111, B0111110 }; </code></pre> <p>But I dont know how to parse it to x, y positions. Can someone help me? Do you know better way to store characters that is easily readable by human? Thanks</p>
<p>To get the value at a particular location, use this code:</p> <pre><code>boolean val = zero[y] &amp; ((B1 &lt;&lt; maxX) &gt;&gt; x); </code></pre> <p>where <code>y</code> is the y position from 0 to <code>zero.length</code>, <code>maxX</code> is the length of the binary constants minus one (in this case, it would be 6), and <code>x</code> is the x position from 0 to <code>maxX</code>.</p> <p>For more information, see <a href="http://arduino.cc/en/Tutorial/BitMask" rel="nofollow">BitMask</a>.</p>
4862
|arduino-uno|library|
AttachInterrupt in a library
2014-11-04T01:33:43.410
<p>I'm having trouble adding attachInterrupt in a library that I am creating. I researched a lot, and I noticed that this is a common mistake, but do not quite understand the answers I found.</p> <p>The error in question is this:</p> <pre><code>sketch_nov04a.ino: In function 'void setup()': sketch_nov04a:10: error: argument of type 'void (Teste::)()' does not match 'void (*)()' </code></pre> <p>My library is as follows: </p> <p><strong>Teste.h</strong></p> <pre><code>#ifndef TESTE_H #define TESTE_H #include &lt;Arduino.h&gt; class Teste { public: volatile long lastWindIRQ; volatile byte windClicks; void wspeedIRQ(); }; #endif </code></pre> <p><strong>Teste.cpp</strong></p> <pre><code>#include "Teste.h" void Teste::wspeedIRQ() { if (millis() - this.lastWindIRQ &gt; 10) { this.lastWindIRQ = millis(); this.windClicks++; } } </code></pre> <p><strong>my implementation</strong></p> <pre><code>#include &lt;Teste.h&gt; Teste teste; void setup() { Serial.begin(9600); pinMode(2, INPUT); digitalWrite(2, HIGH); attachInterrupt(0, teste.wspeedIRQ, FALLING); } void loop() { Serial.println(teste.windClicks); delay(3000); } </code></pre> <p><strong>EDIT</strong>: Updated the error and corrected the problem cited by Ignacio</p>
<p>Normally you should use digitalPinToInterrupt(pin) to translate the actual digital pin to the specific interrupt number not the pin switch comparison attachInturrupt( , , )that is limited to pin 2,3 on an arduino uno ...or if you spend more money well... here's a list.</p> <pre><code>Board Digital Pins Usable For Interrupts Uno, Nano, Mini, other 328-based 2, 3 Mega, Mega2560, MegaADK 2, 3, 18, 19, 20, 21 Micro, Leonardo, other 32u4-based 0, 1, 2, 3, 7 Zero all digital pins, except 4 MKR1000 Rev.1 0, 1, 4, 5, 6, 7, 8, 9, A1, A2 Due all digital pins all digital pins (Only pins 2, 5, 7, 8, 10, 11, 12, 13 work with CHANGE </code></pre> <p>delay() won't work b/c values won't return from millis() (don't ask why) <a href="https://www.arduino.cc/en/Reference/AttachInterrupt" rel="nofollow noreferrer">https://www.arduino.cc/en/Reference/AttachInterrupt</a> explains how to use inturrupts like let me recite the beggining </p> <p>Interrupts are useful for making things happen automatically in microcontroller programs, and can help solve timing problems. Good tasks for using an interrupt may include reading a rotary encoder, or monitoring user input.... blah blah</p> <p>what pete didn't mention is what Interrupt Service Routines were... and how these special functions have unique limitations other functions like in c++ do not.... from c-strings to structs to overloading to f-structs to t-templates. ISR's are as short as possible and should not return anything! if your cheap and don't want to spend more than $5 for a arduino you can use sketch to use multiple isr's you can set them up as priority</p> <p>but your non member functions should be volatile and global... and millis() relies on interrupts to count, so it will never increment inside an ISR. Since delay() requires interrupts to work, it will not work if called inside an ISR. micros() works initially, but will start behaving erratically after 1-2 ms. delayMicroseconds() does not use any counter, so it will work as normal. and .... global variables are used to pass data between an ISR and the main program. To make sure variables shared between an ISR and the main program are updated correctly, declare them as volatile.</p>
4871
|programming|sketch|
Many "expected `)' before ';' token" errors
2014-11-04T19:35:51.860
<p>As the title suggests, I have many "expected `)' before ';' token" errors. The issue is, I have this stuff in. So now I am confused, why am I getting this if the things are there.</p> <p>I am new here and had an issue with adding code, so here is the pastebin link to it: <a href="http://pastebin.com/4WXxsXkB" rel="nofollow">http://pastebin.com/4WXxsXkB</a></p> <p>And here is the the pastebin link to the error: <a href="http://pastebin.com/QyehP86M" rel="nofollow">http://pastebin.com/QyehP86M</a></p> <p>Does anyone understand how this could happen?</p>
<p>You have two #define statements at the top of your code </p> <pre><code>#define trigPin 3; #define echoPin 2; </code></pre> <p>The way <code>#define</code> works is that it replaces every instance of the name with everything after it on the line so <code>trigPin</code> is being replaced with <code>3;</code> as opposed to <code>3</code> as intended.</p> <p>Fixing this should solve some of your problems.</p>
4875
|serial|python|
How to send two different sets of int numbers over serial?
2014-11-05T01:04:35.323
<p>I have a project that require for the main computer to do most of the processing then for it to send the X and Y coordinates of this processing to the arduino. This at the time didn't seem very hard but now that I have started to dive into serial some more I am completely confused. All of the example I have seen for serial only consist of 1 set of numbers and rather confusing. </p> <p>The Arduino code I kinda want to go like this <a href="http://pastebin.com/aLJfEExw" rel="nofollow">http://pastebin.com/aLJfEExw</a> (I know this is probably completely wrong but I am pretty lost right now)</p> <p>The Python code is this right now <a href="http://pastebin.com/4aN4dnSC" rel="nofollow">http://pastebin.com/4aN4dnSC</a></p> <p>If you guys could help explain this better for me it would be amazing. I understand that my code is probably wrong. So if you guys could provide an example of how to send the two different sets of int's it would be amazing. Because I am completely and utterly lost. </p>
<p>I wrote a communication protocol for arduino to node.js over Serial. I sent a buffer of bytes using <code>Serial.write()</code> and read it into a buffer. This allows you to send as many numbers as you want. To send long (16 bit) numbers, you simple need to loop over two at a time combining:</p> <p>C++:</p> <pre><code>long int a = 0x9A44; uint_8t b = ( a &amp; 0xFF00 ) &gt;&gt; 8; uint_8t c = a &amp; 0x00FF; </code></pre> <p>Python:</p> <pre><code>a = ( b &lt;&lt; 8 ) &amp; 0xFF00 | c &amp; 0x00FF </code></pre>
4881
|serial|arduino-mega|
Arduino Mega 2560 RFID Serial Communication
2014-11-05T09:39:14.707
<p>I have an RFID reader: <a href="http://img.tradeindia.com/fp/1/641/264.jpg" rel="nofollow">http://img.tradeindia.com/fp/1/641/264.jpg</a></p> <p>Something like above along with ITEAD TFT shield &amp; GSM Modem. The RFID reader has an RS-232 port as well as GND, TX and 5V pins. I am using an Arduino Mega 2560 board. I have connected the TX, GND of RFID reader to RX3 pin 15 / GND (pin) of Arduino. Note I am supplying 12 V to RFID via an adapter.</p> <p>Note the ITEAD TFT shield consumes the TX0, RX0 pins—so I cannot make use of the RX0 and TX0 pins. Though I have not written the code for GSM modem.</p> <p>Now while running the program below, I am getting junk output both in my TFT display as well as the serial monitor:</p> <pre><code>#define __AVR__ #include &lt;UTFT.h&gt; // Declare which fonts we will be using extern uint8_t SmallFont[]; extern uint8_t BigFont[]; extern uint8_t SevenSegNumFont[]; UTFT myGLCD(ITDB24,59,58,57,56); String myString = ""; void setup() { Serial3.begin(9600); myGLCD.InitLCD(); myGLCD.clrScr(); } void loop() { myGLCD.setFont(BigFont); if (Serial3.available()) { int inByte = Serial3.read(); myString += String(inByte); } if(myString.length() == 10) myGLCD.print(myString, CENTER, 0); } </code></pre> <p>TFT Screen output:</p> <p>1310494848</p> <p>Serial Monitor Output: non printable junk character.</p> <p>The value is incorrect, I am pretty sure, what am I doing wrong?</p> <p>I found that the ITEAD shield is sending or rather using RX0/TX0 pins very frequently—some data is going through.</p> <p>BTW what is the functionality of <a href="http://arduino.cc/en/Tutorial/SoftwareSerialExample" rel="nofollow">http://arduino.cc/en/Tutorial/SoftwareSerialExample</a>?</p> <p>How can I use 3 different Serial I/Os individually at the same time without disturbing any other I/O?</p>
<p>i think the RFID is a other baud rate e.g 115200.. i dont know the device, i dont know if this is the problem, but test it :)</p>
4884
|motor|lcd|
Stack arduino, motor shield and lcd shield
2014-11-05T08:39:36.003
<p>I made arduino-stack which consists of arduino r3, robotdf motor shild and robotdf lcd shield. But motor shield and lcd use same pins 4 and 5, so we have a conflict of pins. Can i use other pins?</p>
<p>Stack one shield on top of the Arduino itself and connect the other shield using wires. This way you can pick your own pin assignment for the 'external' shield.</p> <p>Be careful when using a specific library though, sometimes the used pins are hard-coded in the library itself. Modifying the .h and .cpp files for the library is possible, so you could (hard code) assign your own used pins.</p>
4889
|arduino-uno|serial|programming|sketch|
Sending Serial Hex Command from Pin 1 (Tx)
2014-11-06T02:39:18.020
<p>Using Arduino Uno with 3.5mm Jack connected to ground and pin 1 for TX</p> <p>Need to send two commands I want to send 0XAA13FE010113 for Mute on, and 0XAA13FE010012 for Mute off.</p> <p>Simple Serial Command to turn Monitor Mute on and off every 5 seconds....</p> <p>tried everything byte character, array, write with hex, print :(</p> <p>Thx for a helping a rookie I want to impress my team </p> <hr> <p>Ideal quick answer below. thx to @martynas </p> <pre><code>uint8_t muteON[] = { 0xAA, 0x13, 0xFE, 0x01, 0x01, 0x13 }; uint8_t muteOFF[] = { 0xAA, 0x13, 0xFE, 0x01, 0x00, 0x12 }; .... void loop() { Serial.write( muteON, sizeof(muteON) ); delay(5000); // wait for 5 second Serial.write( muteOFF, sizeof(muteOFF) ); delay(5000); // wait for 5 second } </code></pre>
<p>there are 6 bytes just make </p> <pre><code>byte muteON[] = {0xAA,0x13,0xFE,0x01,0x01,0x13}; byte muteOFF[] = {0XAA,0x13,0xFE,0x01,0x00,0x12}; ... /* To send mute ON comand */ for(byte i =0;i&lt;sizeof(muteON);i++)(Serial.write(muteON[i])); /* To send mute OFF comand */ for(byte i =0;i&lt;sizeof(muteOFF);i++)(Serial.write(muteOFF[i])); </code></pre>
4896
|uploading|arduino-leonardo|
Unable to upload sketch to Leonardo
2014-11-06T12:18:19.433
<p>I'm really at my wits end. For a couple of hours I have been programming a custom board that uses everything as on the Arduino Leonardo. A few hours ago I am not able to upload anymore.</p> <p>I get the following error:</p> <pre><code> avrdude: error: buffered memory access not supported. Maybe it isn't a butterfly/AVR109 but a AVR910 device? </code></pre> <p>I've tried everything from re-installing the IDE, re-installing the board in Device Manager, changing the COM Port. I really just don't know anymore.</p> <p>Here is some more data that might be relevant or useful:</p> <pre><code> Using Port :\\.\COM6 Using Programmer : avr109 Overriding Baud Rate : 57600 AVR Part : ATmega32U4 Chip Erase delay : 9000 us PAGEL : PD7 BS2 : PA0 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 </code></pre> <p>[EDIT] I've now checked the battery (yes with a multimeter), it is fully charged, as it charges when the USB is connected. I've also tried a different computer, along with a different USB cable. </p>
<p>Try this:</p> <p>First: you must find the COMx used for your "Arduino Leonardo" in the "Device Manager" of Windows.</p> <p>Second: make double click to see the properties of the device, and go to the "Port configuration tab"</p> <p>Third: enter in "Avanced Options" and deactivate "Use FIFO buffers", and accept all changes.</p>
4913
|sensors|shields|lcd|arduino-nano|ethernet|
Arduino Nano and a 3.3v Ethernet shield
2014-11-08T04:17:10.630
<p>I plan on purchasing <a href="http://www.ebay.com/itm/3PCS-Nano-V3-0-ATmega328-controller-Board-5V-16M-CH340G-USB-Driver-For-Arduino-/381019048475?pt=LH_DefaultDomain_0&amp;hash=item58b6814a1b" rel="nofollow">a Nano clone</a>, an Ethernet shield <a href="http://www.ebay.com/itm/New-ENC28J60-Ethernet-LAN-Network-Module-For-Arduino-SPI-AVR-PIC-LPC-STM32-BDRG-/301354703227?pt=LH_DefaultDomain_0&amp;hash=item462a23d97b" rel="nofollow">(ENC28J60)</a>, an LCD and a DHT22 humidity + temperature sensor. This will be used in a wine cellar to monitor relative humidity and temperature. </p> <p>The DHT sensor, LCD and Nano all operate on 5V logic. The Ethernet shield does not operate at 5V, but rather at 3.3V. </p> <p>Does the Nano have a way to connect the two, will they work anyway (probably not), or should I use a CD4050 that is recommended on adafruit? </p> <p>Any guidance is appreciated; I'm still amazed in what $10 in parts can do.</p> <p>Also, in regards to the DHT22 sensor, what do I need in terms of a resistor? I've seen some people say you absolutely need a 4.7K resistor on the data pin for "pull up", and others who say it's unnecessary. Can someone give a definite answer, either way?</p> <p>Edit, wrong link on my nano clone.</p>
<p>Just get <a href="http://www.ebay.com/itm/3-3V-5V-ENC28J60-LAN-Ethernet-Network-Module-Dual-MOS-For-Arduino-MCU-AVR-51-LPC-/171310795997?pt=LH_DefaultDomain_0&amp;hash=item27e2eb4cdd" rel="nofollow">one with a 3.3v regulator on it</a>. PS logic levels are allowed to be 5v.</p> <p>DHT22 and LCD will also work fine on 3.3v so, alternatively, you could also get a 3.3v Nano.</p> <p>The resistor value for the DHT22 depends on the length of wire between the DHT and Nano. Just buy them to be sure, or get a breakout board that already has them on the board (along with a capacitor, which is nice).</p>
4930
|arduino-uno|avrdude|osx|
Make upload stuck on osx 10.10 bare-arduino-project
2014-11-09T16:27:23.450
<p>I followed the instructions in <a href="https://github.com/WeAreLeka/Bare-Arduino-Project/blob/master/INSTALL.md" rel="nofollow">here</a>, including to use arduino IDE v 1.0.5, but when I tried to <code>make upload</code> it stuck. I can upload it when using Arduino IDE.</p> <p>Here is what I got:</p> <pre><code> mkdir -p /Users/bagustrihatmaja/Documents/Projects/MyAwesomeProject/bin/mega328/mySecondProject /Applications/Xcode.app/Contents/Developer/usr/bin/make reset /Users/bagustrihatmaja/Documents/Projects/MyAwesomeProject/Arduino-Makefile/bin/ard-reset-arduino /dev/cu.usbmodem1421 /Applications/Xcode.app/Contents/Developer/usr/bin/make do_upload /usr/local/bin/avrdude -q -V -D -p atmega328p -c arduino -b 57600 -P /dev/cu.usbmodem1421 \ -U flash:w:/Users/bagustrihatmaja/Documents/Projects/MyAwesomeProject/bin/mega328/mySecondProject/mySecondProject.hex:i </code></pre> <p>What did I miss?</p> <p>I use: Bare-Arduino-Project, OSX 10.10, XCode 6.1, Arduino Uno, <a href="http://pastebin.com/cR79Sqqz" rel="nofollow">my Makefile</a></p>
<p>I'm the maintainer of the Bare-Arduino-Project, thanks for using it :)</p> <p>Have you installed <code>pyserial</code> and <code>avrdude</code>?</p> <p>To install <code>avrdude</code> just run <code>brew install avrdude</code> and to install <code>pyserial</code>, you need <code>python installed</code>, then you can run <code>pip install pyserial</code>.</p> <p><a href="https://github.com/WeAreLeka/Bare-Arduino-Project/blob/master/INSTALL.md#3-install-pyserial" rel="nofollow">https://github.com/WeAreLeka/Bare-Arduino-Project/blob/master/INSTALL.md#3-install-pyserial</a></p> <p>Hope it helps :)</p> <p>Next time, feel free to open an issue in the Github repo as it might also help others.</p> <p><strong>EDIT:</strong> my bad, I did not read your Makefile carefully!</p> <p>the problem is with:</p> <pre><code>BOARD_TAG = mega328 # it should be BOARD_TAG = uno </code></pre>
4932
|arduino-uno|pwm|
What is the best way to measure PWM signals ( pulseIn ) with the Arduino via a Raspberry Pi?
2014-11-09T21:20:09.047
<p>I connected my Arduino Uno to my raspberry via USB serial. I'm able to read out both digital and analog pins of my Arduino using the Python nanpy library (v.0.8). However, I can't find support for the pulseIn() function. It seems nanpy doesn't support pulseIn() at all.</p> <p>What is the best way to measure PWM signals with the Arduino and forward the results to the Raspberry Pi? </p> <p>I am able to measure PWM using the Arduino GUI, however I would to take PWM samples at fixed time intervals over a long period of time and combine this data with other measurements that my Raspberry is making.I also tried pyFirmata, but it doesn't support pulseIn() measurements either.</p>
<p>You can just have a sketch in the arduino that takes the measurements at whatever interval you want using the <code>analogRead(pin)</code> function and then forward those results to the raspberry pi via serial using <code>Serial.print(whatever you want here)</code>. If you don't know how to use serial with arduino just go to their site, they have very good documentation. Hope that helps :)</p>
4933
|sensors|bare-conductive|
Sense distance with Bare Conductive's Touch Board
2014-11-09T21:52:21.973
<p>How can I sense distance with Bare Conductive's Touch Board, like they suggest in <a href="https://www.youtube.com/watch?v=Y3eSrUQTesg&amp;t=27s" rel="nofollow">their product video</a>?</p> <p>I know how I can set the touch and release thresholds, so my Touch Board is more sensitive and triggers before I touch a sensor. What I want to do is get the information how near I am. Not in centimeters or so, but a simple value telling me when I'm nearer to or farther from the sensor like in the video.</p>
<p>As a member of the Bare Conductive team, I can tell you that looking at the <a href="https://github.com/BareConductive/mpr121-grapher" rel="nofollow">grapher</a> will be helpful to you. The grapher is a processing sketch that requires the Touch Board to be running the <a href="https://github.com/BareConductive/mpr121/tree/public/MPR121/Examples/DataStream" rel="nofollow">Datastream</a> code. Datastream will give you the sort of raw electrode data that you're looking for.</p>
4938
|programming|button|
Getting Push Button Logic To Stick?
2014-11-10T14:19:13.297
<p>I'm trying to get a sensor to activate if a push button is clicked. And deactivate when a certain condition is met and reactivate when the push button is pressed again.</p> <pre><code>#include &lt;SPI.h&gt; // Included for SFE_LSM9DS0 library #include &lt;Wire.h&gt; #include &lt;SFE_LSM9DS0.h&gt; #define LSM9DS0_XM 0x1D // Would be 0x1E if SDO_XM is LOW #define LSM9DS0_G 0x6B // Would be 0x6A if SDO_G is LOW // Create an instance of the LSM9DS0 library called `dof` the // parameters for this constructor are: // [SPI or I2C Mode declaration], [gyro I2C address], [xm I2C address] LSM9DS0 dof(MODE_I2C, LSM9DS0_G, LSM9DS0_XM); const byte INT1XM = 4; // INT1XM tells us when accel data is ready //const byte INT2XM = 8; // INT2XM tells us when mag data is ready //const byte DRDYG = 7; // DRDYG tells us when gyro data is ready const int buttonPin = 15; // the number of the pushbutton pin int buttonState = 0; double X; double Y; double Z; void setup(){ pinMode(INT1XM, INPUT); pinMode(buttonPin, INPUT); Serial.begin(9600); Serial1.begin(9600); // Start serial at 115200 bps // Use the begin() function to initialize the LSM9DS0 library. // You can either call it with no parameters (the easy way): uint16_t status = dof.begin(); // Or call it with declarations for sensor scales and data rates: //uint16_t status = dof.begin(dof.G_SCALE_2000DPS, dof.A_SCALE_6G, dof.M_SCALE_2GS); // begin() returns a 16-bit value which includes both the gyro and // accelerometers WHO_AM_I response. You can check this to make sure // communication was successful. // Serial.println(status, HEX); setODR(); } void loop(){ buttonState = digitalRead(buttonPin); //Read push button logic. // Serial.println(buttonState); if (buttonState == 1) { //if push button is pressed printAccel(); //print sensor data } } void printAccel() { // Only read from the accelerometer if the accel interrupts, // which means that new data is ready. if (digitalRead(INT1XM)) { // Use the readAccel() function to get new data from the accel. // After calling this function, new values will be stored in // the ax, ay, and az variables. dof.readAccel(); //Serial.print("A: "); // Using the calcAccel helper function, we can get the // accelerometer readings in g's. X=dof.calcAccel(dof.ax); Y=dof.calcAccel(dof.ay); Z=dof.calcAccel(dof.az); Serial.print(X); Serial.print(", "); Serial.print(Y); Serial.print(", "); Serial.println(Z); // Serial1.println(Z); fall(); //jump to check condition } } void setODR(){ dof.setAccelODR(dof.A_ODR_25); dof.setAccelScale(dof.A_SCALE_16G); } void fall(){ if(-0.08&lt;X &amp;&amp; X&lt;0.08){ if(-0.08&lt;Y &amp;&amp; Y&lt;0.08){ if(-0.08&lt;Z &amp;&amp; Z&lt;0.08){ Serial1.println("N"); Serial.println("Fallen!"); loop(); //if condition is met, jump to loop to wait for push button to be pressed again. } } } //else{ printAccel(); //else continue printing sensor data //} } </code></pre> <p>However I am having some trouble getting it to work, above is what I have worked out thus far.</p>
<p>You'll need to store whether the button has been pressed.</p> <pre><code>bool buttonActivated = false; ... void loop(){ buttonState = digitalRead(buttonPin); //Read push button logic. if (buttonState == 1 ) { buttonActivated = true; } if( buttonActivated ) { printAccel(); //print sensor data } } </code></pre> <p>to deactivate, use:</p> <pre><code>buttonActivated = false; </code></pre>
4950
|arduino-pro-mini|voltage-level|battery|
Powering a 5V Arduino Pro Mini with 3.3V
2014-11-11T13:00:00.863
<p>I want to run the 5V board at 3.3V because I can get the 5V version cheaper than the 3.3V version.</p> <p>I read that you can power the Arduino Pro Mini with a battery by connecting the battery to the 5V pin, bypassing the regulator.</p> <p>Somewhere else I read that the only difference between a 3.3V and 5V Pro Mini is the regulator.</p> <p>Are these assumptions correct? If yes, can I use a 5V Pro Mini like a 3.3V by powering it with a 3V Battery on the 5V pin?</p>
<p>Im feeding 5V pro mini clone with 2 AA battery, to VCC pin, about 3V and it works normally. It consumes few current compared to 5V. <a href="https://i.stack.imgur.com/CwZiJ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CwZiJ.jpg" alt="consuming at 3V"></a> <a href="https://i.stack.imgur.com/Lb51E.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Lb51E.jpg" alt="at 5V"></a> And you can see what it the setup in <a href="https://twitter.com/anunidentified/status/1069283092135845888?s=19" rel="nofollow noreferrer">here</a>. Also <a href="https://youtu.be/381Rg5YDmRM" rel="nofollow noreferrer">this</a> video can be useful.</p>
4952
|arduino-uno|spi|potentiometer|
Digital Potentiometer not fading LED
2014-11-11T14:32:28.540
<p>So I am trying to test what will eventually be a Arduino controlling 3 110V motors that are currently controlled by an analog pot. But more on that later.</p> <p>I am trying to test out using a digital pot (never have before) and am running into some issues with tutorials I have found online. For now, I want to control a LED with the digital pot (<a href="http://dlnmh9ip6v2uc.cloudfront.net/datasheets/Components/General%20IC/22060b.pdf" rel="noreferrer">Spec Sheet</a>) so that the LED fades in and fades out in a continuos loop.</p> <p>Here is the <a href="http://www.instructables.com/id/Digital-Potentiometer-MCP41100-and-Arduino/?ALLSTEPS" rel="noreferrer">tutorial I followed</a>. It uses a different chip model but it seems from the pot I am using that the pins are the same. (I could be wrong?)</p> <p>I double and triple checked the wiring and it matches below.</p> <p><img src="https://i.stack.imgur.com/urSnK.jpg" alt="Wiring Diagram"></p> <p>Here is the code I am running (slightly modified from the tutorial, also tried the tutorial code)</p> <pre><code>#include &lt;SPI.h&gt; byte address = 0x11; int CS= 10; int i=0; void setup() { pinMode (CS, OUTPUT); SPI.begin(); } void loop() { for (i = 0; i &lt;= 128; i++) { digitalPotWrite(i); delay(10); } delay(500); for (i = 128; i &gt;= 0; i--) { digitalPotWrite(i); delay(10); } } int digitalPotWrite(int value) { digitalWrite(CS, LOW); SPI.transfer(address); SPI.transfer(value); digitalWrite(CS, HIGH); } </code></pre> <p>As a result of the two above, I have an LED that stays lit (at about 50% it seems) and does not fade in/out at all.</p> <p>Being relatively new to wiring and EE in general, is there a better way to replicate an analog pot without using a digital pot? Can I just use PWM to control it? Why would the LED be just staying lit?</p> <p>Thanks!</p>
<p>After studying the datasheet differences between <strong>MCP41100</strong> (digital pot used in the tutorial) and <strong>MCP4131</strong> (the one you get), I found <strong>two major differences</strong> between both:</p> <ol> <li><p>Difference in <strong>resolution</strong>:</p> <ul> <li>MCP41100 has <strong>257 steps</strong> resolution (8 bits + 1): you can see that at the beginning of <a href="http://www.futurlec.com/SFMicrochip/MCP41100.shtml" rel="nofollow">its datasheet</a></li> <li>MCP4131 has only <strong>129 steps</strong> resolution (7 bits + 1): you can get this information on page 2 of <a href="http://dlnmh9ip6v2uc.cloudfront.net/datasheets/Components/General%20IC/22060b.pdf" rel="nofollow">its datasheet</a></li> </ul></li> <li><p>Difference in <strong>commands formats</strong> sent through SPI; both use one "command byte" followed by a "data byte", but have a diffrent format for their command byte:</p> <ul> <li>MCP41100 command byte is <code>X X C1 C0 X X P1 P0</code> where <code>X is unused</code>, <code>C1 C0</code> is one of 4 possible commands, only 2 being valid commands actually: <code>01</code> (Write data), <code>10</code> (Shutdown), finally <code>P1 P0</code> should be always <code>01</code> for an MCP41100</li> <li>MCP4131 command byte is <code>AD3 AD2 AD1 AD0 C1 C0 D9 D8</code>, where <code>AD3-AD0</code> is the address of the "register" on which to perfom a command. For the MCP4131, the most important address is <code>00</code> which means "volatile wiper 0" (this is what allows you to change the resistance value of the pot), <code>C1 C0</code> is one of 4 possible commands (read data, write data, increment, decrement), in your example the command should be <code>00</code> (write data); finally <code>D9 D8</code> are the high order bits of the value to write to the register, but <code>D9</code> is unused and should always be <code>0</code>. For 257-steps pots, <code>D8</code>is used to have the full resistance scale, otherwise it should be <code>0</code></li> </ul></li> </ol> <p>Now that we know aht your MCP4131 expects as commands passed through SPI, we can take a look at what the tutorial program passes:</p> <pre><code>00010001 value </code></pre> <p>The first byte can be broken down as such:</p> <ul> <li><code>0001</code> address of the pot <strong>wiper register 1</strong> (<strong>not 0</strong>): this wiper does not exist on MCP4131 hecne writing to it will have no impact...</li> <li>00 command bits meaning "Write to register specified in previous address"</li> <li>01 high order bits (D9-D8) of the value to write to the wiper register.</li> </ul> <p>Although I don't have an MCP4131 at hand, I think you should adapt the program as follows:</p> <pre><code>byte address = 0x00; </code></pre> <p>And that should be fine! Indeed, now your program passes:</p> <pre><code>00000000 value </code></pre> <p>Which means "write <code>value</code> (between <code>0</code> and <code>128</code> which matches exactly the 129 steps resolution) to the wiper register 0 of the port".</p> <p>Note that the MCP4131 has more features than the MCP41100 in terms of commands, for instance you could use the special commands "increment" and "decrement", with the advantage they need only one byte (the command byte), e.g.</p> <pre><code>void loop() { for (i = 0; i &lt;= 128; i++) { digitalPotIncrement(); delay(10); } delay(500); for (i = 128; i &gt;= 0; i--) { digitalPotDecrement(); delay(10); } } void digitalPotIncrement() { digitalWrite(CS, LOW); SPI.transfer(0x04); digitalWrite(CS, HIGH); } void digitalPotDecrement() { digitalWrite(CS, LOW); SPI.transfer(0x08); digitalWrite(CS, HIGH); } </code></pre>
4956
|arduino-uno|motor|
Can I use this replacement motor without modifying the circuit?
2014-11-12T18:27:48.117
<p>I have a demo that spins a motor, but the leads on my motor broke. I happen to have another motor lying around that I'd like to swap in, but it's of a different type. Here's my circuit:</p> <p><img src="https://i.stack.imgur.com/ccBRT.png" alt="Spin Motor Spin from Node-Ardx"></p> <p>This is the old (broken) motor: <a href="https://www.sparkfun.com/products/11696" rel="nofollow noreferrer">https://www.sparkfun.com/products/11696</a>. It has an operating voltage range of 1.0 to 3.0V DC and a no load speed of 6600±10% RPM (@1.0V DC, 110mA). </p> <p>The new motor that I'd like to use is part of this kit: <a href="https://www.sparkfun.com/products/12866" rel="nofollow noreferrer">https://www.sparkfun.com/products/12866</a>. It's a 6VDC motor with a No Load Speed of 90±10rpm and a No Load Current of 190mA(max.250mA). </p> <p>I'm running this off a Sparkfun Redboard, which is UNO R3 compatible.</p> <p>Can I swap in the new motor without any circuit changes? Will I have to add additional power for the new motor? Or should I change the circuit with a larger resistor or something else?</p>
<p>Regarding voltage, I think there should be no problem as the datasheet for your replacement motor specifies a "suggested voltage 4.5V DC".</p> <p>However, be careful that there is another important value in motor datasheets: the <strong>stall current</strong>.</p> <p>Simply stated, this is the current consumed by the motor when it tries to rotate but is unable to, due to its too low torque in comparison with the effort needed for rotation, e.g. if it tries to rotate the wheel of a robot that is too heavy.</p> <p>The original motor has a stall current of 0.8A according to its datasheet (you can get it from the link you provided).</p> <p>Your replacement motor has 1A according to the link you provided. </p> <p>These 200mA can make a big difference for the transistor used in your circuit, a <strong>P2N2222A</strong>.</p> <p>Indeed, that transistor is <a href="https://cdn.sparkfun.com/datasheets/Components/General/P2N2222A-D.PDF" rel="nofollow">specified</a> to switch a maximum of <strong>600mA</strong> current at the collector.</p> <p>So in the best case, the motor will run correctly without load, but if you provide some load that makes it stall, then the transistor will raise temperature (you could sense that by approaching your finger) and ultimately would get toasted.</p> <p>Please also note that some poorly designed motors may consume a current near the stall current, due to internal friction (I have already almost grilled a transistor this way...)</p> <p>So my answer is: </p> <ul> <li>you can do it for a simple experiment with no load on the motor</li> <li>if you really want to do something with the motor, take another transistor with a higher <em>Ic</em> current</li> </ul>
4957
|c++|
How can I pass an object as a parameter to a function?
2014-11-12T18:53:59.497
<p>I am making a tiny game, and want to store high-scores. I made a Highscore-class in the top of the sketch file, like this: </p> <pre><code>class Highscore { public: String name; int score; String toString() { return this-&gt;name + " - " + (String)score; } Highscore(String name, int score) { this-&gt;name = name; this-&gt;score = score; } }; setup() { // etc </code></pre> <p>Now. Near the bottom of the sketch, I have a function I want to take a Highscore-object as a parameter, but the compiler will not let me. Example:</p> <pre><code>void writeHighscore(Highscore hs) { File f = SD.open("high.txt", FILE_WRITE); // Do stuff </code></pre> <p>The complation error is as follows:</p> <blockquote> <p>sketch.ino:19:21: error: variable or field ‘writeHighscore’ declared void<br> sketch.ino:19:21: error: ‘Highscore’ was not declared in this scope<br> sketch.ino: In function ‘void setup()’:<br> sketch.ino:64:20: error: ‘writeHighscore’ was not declared in this scope</p> </blockquote> <p>After changing parameter type to String, int or whatever, all the errors go away. I am able to create Highscore-objects INSIDE the <code>writeHighscore()</code> function, but how can I pass objects to it?</p> <p><strong>Edit 1 - Object creation</strong></p> <pre><code>Highscore hs = Highscore("John", 975); Serial.println(hs.toString()); // Prints "John - 975" as expected writeHighscore(hs); // Error </code></pre>
<p>This is a classic example of the IDE "helping" you by generating function prototypes, and not doing it very well. Example code to reproduce:</p> <pre class="lang-C++ prettyprint-override"><code>class Highscore { public: String name; int score; String toString() { return this-&gt;name + " - " + (String)score; } Highscore(String name, int score) { this-&gt;name = name; this-&gt;score = score; } }; void setup () { } void loop () { } void writeHighscore(Highscore hs) { // do stuff } </code></pre> <p>This gives the error:</p> <pre class="lang-C++ prettyprint-override"><code>sketch_jul06b:4: error: variable or field ‘writeHighscore’ declared void sketch_jul06b:4: error: ‘Highscore’ was not declared in this scope </code></pre> <hr> <p>If you look at the output of the IDE preprocessor (you can do this by turning on verbose compilation, and finding out the name of the file it is actually compiling) you see this:</p> <pre class="lang-C++ prettyprint-override"><code>#line 1 "sketch_jul06b.ino" #include "Arduino.h" void setup (); void loop (); void writeHighscore(Highscore hs); #line 1 class Highscore { public: String name; int score; String toString() { return this-&gt;name + " - " + (String)score; } Highscore(String name, int score) { this-&gt;name = name; this-&gt;score = score; } }; void setup () { } void loop () { } void writeHighscore(Highscore hs) { // do stuff } </code></pre> <p>The important part is that it put:</p> <pre class="lang-C++ prettyprint-override"><code>void writeHighscore(Highscore hs); </code></pre> <p><strong>before</strong> where the class is declared.</p> <hr> <p>You can fix the error by simply generating your own function prototype like this:</p> <pre class="lang-C++ prettyprint-override"><code>void writeHighscore(Highscore hs); // function prototype void writeHighscore(Highscore hs) { // do stuff } </code></pre> <p>Now it compiles without errors. It detects your <em>own</em> function prototype, and therefore does not generate its own. The first few lines of the generated file are now:</p> <pre class="lang-C++ prettyprint-override"><code>#line 1 "sketch_jul06b.ino" #include "Arduino.h" void setup (); void loop (); #line 1 </code></pre> <p>That troubling prototype has gone.</p>
4977
|variables|
Assuring an unsigned long int?
2014-11-13T22:23:41.270
<p>Basic question: How far do I have to go to assure that integer math is done correctly? For example, this is probably overdone:</p> <pre><code>unsigned long burnTime = 0UL; unsigned long curBurnTime = 0UL; // Do some stuff that sets the above variables to millis() at various times // Later on... unsigned long adjustedBurnTime = (unsigned long) ((burnTime + curBurnTime) / 1000UL); </code></pre> <p>Would the math be done correctly if I went to a more minimal last statement (since all the elements of the equation are unsigned longs)? Like this:</p> <pre><code>unsigned long adjustedBurnTime = ((burnTime + curBurnTime) / 1000UL); </code></pre> <p>Or even:</p> <pre><code>unsigned long adjustedBurnTime = ((burnTime + curBurnTime) / 1000); </code></pre>
<p>Any good C manual will tell you the result type for each basic math operation on given types. But briefly, the basic math operators return a result as wide as the widest operand, with the narrower operand being widened to match the wider one, if they differ. The same with assignment: assigning a result of a given type to a variable of the same type will not involve any conversion.</p> <p>tl;dr: No, you're not missing anything. You don't need any casts in your example.</p> <p>PS: One thing you do need to be aware of is whether any of your intermediate results will overflow the arithmetic type you're using. For example, the final result may be not exceed an unsigned long but the expressions <code>(burnTime + curBurnTime)</code> must also not exceed it. This is a greater concern with smaller data-types, of course.</p> <p>PPS: Good on you for tackling fixed point arithmetic rather than just reaching for the floating-point library!</p>
4979
|arduino-uno|display|
How can I implement double buffering with an Arduino UNO?
2014-11-14T01:49:19.487
<p>I am creating a tiny game on my Arduino UNO with an Adafruit ST7735 1.8" TFT / SD breakout. I am performing screen operations using the built-in TFT-library.</p> <p>The problem is screen flickering. Even though I take care to prepare data and minimize the time between clearing the screen and writing the new stuff to it, the screen "refresh()" is significant. I heard someone mention something called double buffering, so I read a bit up on it, but I am frankly clueless on how to implement it on an Arduino UNO. </p> <p>Is it possible to implement double buffering on an Arduino UNO to prevent screen flickering, and if so, how?</p> <p>Libraries used:</p> <pre><code>#include &lt;TFT.h&gt; #include &lt;Wire.h&gt; #include &lt;SPI.h&gt; #include &lt;SD.h&gt; </code></pre> <p><br>The screen is "cleared" like this:</p> <pre><code>screen.background(0,0,0); // Clear it screen.text(buf, 10, 25); // Write new stuff </code></pre>
<p>To add to previous answers:</p> <p>Double-buffering is an approach where you <em>write to the actual device</em> - but in an off-screen area. Then you switch to the new area in a single instruction, indistinguishable to the naked eye, rather than clear the visible area and write while it's still being displayed.</p> <p>This requires that the <em>device</em> has extra memory to support the two areas: on-screen and off-screen. Absent that extra memory, then the best that you can do is pre-calculate as much as possible, and write to the screen as fast as possible.</p>
4982
|arduino-mega|string|
How to split in string
2014-11-14T05:55:10.493
<p>I want to split this: </p> <pre><code>char* value = "12;32;blue"; or string value = "12;32;blue"; </code></pre> <p>into this vars:</p> <pre><code>TV = 12; AR = 32; LED = "blue"; </code></pre> <p>is it possible?</p>
<p>For C-strings (<code>char*</code>), your best option (in terms of performance and memory consumption) is to use <a href="http://www.cplusplus.com/reference/cstring/strtok/" rel="nofollow"><code>strtok</code></a>:</p> <pre><code>char* value = "12;32;blue"; char* token = strtok(value, ";"); int TV = atoi(token); token= strtok(0, ";"); int AR = atoi(token); token = strtok(0, ";"); char* LED = token; </code></pre> <p><strong>Note 1</strong>: the code above takes it for granted that <code>value</code> is properly formatted, i.e. contains 3 parts split by <code>;</code>. If it is not sure, then you should add additional checks on <code>token</code> value returned by <code>strtok</code>.</p> <p><strong>Note 2</strong>: <code>strtok</code> is modifiying its <code>value</code> argument, so that at the end of the code above, <code>value</code> will not be equal to <code>12;32;blue</code> any longer.</p> <p><strong>Note 3</strong>: <code>LED</code> variable above will point directly to the character <code>b</code> inside <code>value</code>, which means that if <code>value</code> is modified afterwards, <code>LED</code> might be modified as well.</p>
4983
|arduino-uno|arduino-mega|
Measure Water Flow in literes using Arduino Mega 2560 Board and Water Flow Sensor
2014-11-14T06:28:10.037
<p>I have a water flow sensor with Arduino Megs 2560 board. I am trying to conceptualize the concept to calculate amount of water getting dispensed esp. in 1,2,3,4 and 5 liters quantity. </p> <p>Water flow sensor specification:</p> <p><a href="http://www.seeedstudio.com/wiki/images/b/b7/Water_flow_sensor_datasheet.pdf" rel="nofollow">http://www.seeedstudio.com/wiki/images/b/b7/Water_flow_sensor_datasheet.pdf</a></p> <p>I would connect the sensor input to any pin from 22-53 pin.</p> <p>Suppose I connect to ping 23 so in my setup() function I would add:</p> <pre><code>attachInterrupt(23, pulseCounter, FALLING); </code></pre> <p>where pulseCounter is an interrupt function triggered on each signal generated from sensor and increments a variable</p> <pre><code>void pulseCounter() { // Increment the pulse counter pulseCount++; } </code></pre> <p>Now how do I calculate the flowrate and water dispensed in milliliters using this information? How do I know the freqz of the MCU (which is required as water dispensed per pulse is different for different MCUs)?</p>
<p>the pulse rate can be derived without knowledge of the CPU clock speed. To achieve the pulse rate from your sensor input you can do two things:</p> <ol> <li>count the pulses <strong>dn</strong> within a certain (i.e. fixed) interval <strong>T</strong> of time) or</li> <li>measure the time <strong>dt</strong> between two pulses.</li> </ol> <p>I'll come back later on this concerning accuracy.</p> <p>To measure time, you can use the function millis(). This function returns you the milliseconds since bootup as an integer upon calling it. Method 2 is rather simple to implement. </p> <ul> <li>Setup three global integers <em>a</em>, <em>b</em> and <em>c</em>.</li> <li>At the end of setup set <em>a</em> to current millis();</li> <li>In your ISR set b to current millis();</li> <li>Also in ISR: set a=b;</li> <li>calculate <em>c=b-a</em> (i.e. your <strong>dt</strong>);</li> </ul> <p>c holds your current full wave pulse length in milliseconds, which is updated every pulse. You can derive your flow then from it. </p> <p>The first method uses a counter as demonstrated in your suggestion. You then need a timer outside your ISR, two variables <em>d</em> and <em>e</em>. Either you poll millis() in your main "loop()" or you install a timer interrupt, both will work here. </p> <ul> <li>At the end of setup set <em>d</em> to current millis();</li> <li>If your predefined time <strong>T</strong> is passed (by comparing <em>d</em> with millis(), </li> <li>save your counted pulses to <em>e=pulseCount</em></li> <li>reset: <em>pulseCount=0</em></li> </ul> <p><em>e</em> holds your pulse count during interval <strong>T</strong>, from which you can derive your pulse rate.</p> <h2>Accuracy</h2> <p>Method 1's accuracy increases with higher <strong>T</strong> and higher flow speeds. Therefore the update rate of your measurement is low. By changing <strong>T</strong> you can easily increase accuracy on cost of responsiveness. This is perhaps a good idea, if you have pulsating flows in your tubings, or the sensor is a bit rattling. </p> <p>Method 2's accuracy increases with lower flow speeds. It is best to measure very low flow speeds. Update frequency is minimal (1/<strong>dt</strong>).</p> <p>Regarding this sensor you should calibrate it yourself. It is a cheap and rugged device (I'm using it, too), but its output depends on several parameters like mounting position, fluid viscosity and so on. Make sure, there are no bubbles, foam or contaminants in your fluid systems as they garble the results effectively. </p> <p>n.b.: make sure to take care of an overflow of millis(). </p>
4997
|prototype|
Proto Shields wthout breadboard?
2014-11-15T12:03:06.363
<p>I want to use a proto shield (brand is unimportant) and solder some components to it, to make something more premanent than using a breadboard.</p> <p>My question is can the components be soldered directly to the middle area where there are a lot of small holes?</p> <p>I would assume this is possible, but everywhere I look people add mini breadboards to their proto shields.</p> <p>If it's possible, then I assume components and wires can't just be connected in a row like on a breadboard and would instead need some solder between 2 holes where for example a component and seperate wire are connected?</p>
<p>There are many different types of photo-shields, sometimes they have interconnected rows or they just have individual solder holes or even breadboards. What you get all depends on what you are doing. My personal favorite are the interlocked rows so I buy that and use a breadboard while I am developing my project then take off the breadboard and solder everything into place.</p> <p><a href="http://rads.stackoverflow.com/amzn/click/B00K992NTI" rel="nofollow">Example of non interlocked rows</a> and an <a href="http://rads.stackoverflow.com/amzn/click/B006SJSBBM" rel="nofollow">My favorite proto-shield, it has a little of both kinds</a></p>
5023
|arduino-leonardo|debugging|
Arduino hangs after 3-4 minutes on battery power, but not on USB
2014-11-17T19:46:37.903
<p>I have a simple sketch running on a BE Leonardo-compatible board.</p> <p>It reads input from a potentiometer, and outputs to two RGB LEDs which change colour over time - in a different pattern if certain inputs are received.</p> <p>Other than that, the only code is serial I/O for debug purposes. (It's disabled using a #define in the running version, to prevent serial buffer overflow when not connected.)</p> <p>When the board is powered by USB, everything works.</p> <p>When the board is powered by 9V battery, after about 4 minutes it hangs - the LEDs go off, and the L13 light on the board starts glowing at varying strength. (There is nothing connected to pin 13.) Even the reset button doesn't work.</p> <p>If the board is then connected to the computer's USB port, after a few seconds the hang clears and the program resumes.</p> <p>Can anyone offer a possible explanation for (and solution to) this fault?</p>
<p>As somebody else suggested, 9V batteries are pretty weak. They only provide a very small number of mAh (milliamp/hours) before their voltage starts to drop. Once the voltage drops to around 7 volts, the regulator in the Arduino can't keep providing 5 volts, so your Arduino resets.</p> <p>Wire up 6 AA batteries in series. That will provide a much "stiffer" 9 volt supply (more instantaneous current) plus a lot more mAh of total power. If you REALLY want long life, wire up 6 C or D batteries in series, or an external 9V supply through a "wall wart" power supply.</p>
5037
|arduino-uno|
How to ensure electronic components make good connection with breadboard
2014-11-18T04:02:41.497
<p>I just began following the projects in the Arduino Projects Book included in the Arduino Starter Kit.</p> <p>While using LEDs, as in the first few examples of the book, I am having a difficult time keeping them in contact with the breadboard. I can usually move the LED around until it turns on, but even a push of a button can make it lose contact with the board. I haven't used much more than switches, jumpers, LEDs and resistors, so I don't know if any of the other components behave the same. For the more complex projects, it seems like it would be hard to tell if you have it setup properly if you can't be sure the components are making a connection with the breadboard.</p> <p>Is there a particular way to get all the components to sit nicely in the breadboard, or to modify them to do so?</p>
<p>Sounds like you may not be pushing the leads into the board,I find long nose pliers handy for components with thicker leads.</p>
5053
|arduino-uno|
Infrared interruption counter
2014-11-19T09:10:48.537
<p>Is it possible to create a infrared based interruption counter with an Arduino Uno? If yes, then what additional hardware would be necessary?</p>
<p>You can use photo any transmissive or reflective photo interrupter (wire or TH) ideally with integrated Schmitt trigger and connect to IRQ driven AVR input to have quick trigger reaction. For production is cheaper photo interrupter with external Schmitt but for prototyping it does not matter. Don't forget serial resistor to limit current. </p> <p>Search e.g. "photo interrupter Schmitt" at Farnell.</p>
5056
|serial|uploading|bluetooth|
Blend Micro uploading sketch
2014-11-19T11:35:55.307
<p>I have just got the <a href="http://redbearlab.com/blendmicro/" rel="nofollow noreferrer">Blend Micro</a> board. After following the <a href="http://redbearlab.com/getting-started-blendmicro" rel="nofollow noreferrer">getting started tutorial</a> I can't manage to upload sketches on the board. Now, in Arduino v. 1.0.6 I see the voices</p> <ul> <li>Blend</li> <li>Blend Micro 3.3V/8Mhz</li> <li>Blend Micro 3.3V/16Mhz (Overclock) as in this picture:</li> </ul> <p><img src="https://i.stack.imgur.com/pzKcF.png" alt="enter image description here"></p> <p>While the L Led is switch on if I upload the sketch the TX and RX leds stay off. The modified Arduino IDE says "Done uploading". As port I choose /dev/tty.Bluetooth-Serial-1 and I don't see any other port and I think this is critical.</p> <p>But if I open the Android BLE application BLE Controller, after tried to upload the <strong>BLEControllerSketch</strong> (from RBL_nRF8001 libraries) it finds the board but print the error <strong>No Response from the BLE Controller sketch</strong>. If I try with <strong>SimpleChat</strong> example and the SimpleChat Android application if finds the board but prints only "Hello World" and nothing else if I send strings from the android app.</p> <p>Any kind of advice?</p> <p>EDIT</p> <p>I am on a Mac 1.8.5. I have tried also with Codebender, but anything change: I can't see the <code>/dev/tty.usb*</code> in the listed ports</p>
<p>For anyone else who is having an issue with this. What worked for me, was replacing the cable with a shorter cable. I could of been using a charging only usb cable or the cable was long enough to not upload correctly. </p>
5060
|arduino-uno|softwareserial|
Arduino SoftwareSerial library basic example doesn't work
2014-11-19T13:00:20.677
<p>I come to you again because I have a problem with the Arduino SoftwareSerial library. With a basic example I fail to see results in the serial monitor.</p> <p>The basic code example:</p> <pre class="lang-C++ prettyprint-override"><code>#include &lt;SoftwareSerial.h&gt; SoftwareSerial mySerial(10, 11); void setup() { mySerial.begin(4800); } void loop() { mySerial.println("HELLO"); delay(100); } </code></pre> <p>I guess it should show the string "HELLO" on the serial port, but nothing appears. I have found that the baud setting is correct. The hardware is simple. Only an Arduino Uno v3 without any connected component.</p>
<p>Addition to <code>Peter R. Blommfield</code></p> <p>What is your problem?</p> <p>Connect your device, run this sketch and you are good to go :)</p> <pre><code>/* TEST */ #include &lt;SoftwareSerial.h&gt; /* Connect device Rx - 10, Tx - 11 */ SoftwareSerial mySerial(10, 11); void setup() { Serial.begin(9600); // This will communicate with PC via USB mySerial.begin(4800); // This will communicate with device via 10,11 pins with 4800 baud rate } void loop() { Serial.println("HELLO"); // Sends string to PC to Serial Monitor mySerial.println("HELLO"); // Sends string to device delay(100); // Waits here 100ms and then goes on } </code></pre>
5064
|arduino-uno|led|resistor|
how to calculate correct resistor value to use with LEDs Potentiometer and other devices?
2014-11-19T14:21:06.737
<p>I have been following <a href="http://arduino.cc/en/Tutorial/Fade" rel="nofollow">http://arduino.cc/en/Tutorial/Fade</a> to fade and LED. But I don't know why they are using a 220 Ohm resistor. According to Ohms law if LED is of 2.2 V and it runs on 0.025Amps and is connected to 5V pin of Arduino then the resistor should be of 120 Ohms but why we are using 120 Ohm resistor ? One more thing. How can I collect value of resistor to be used with different output and input devices ?</p> <p>Thanks in advance</p>
<p>If the LED has a forward voltage of 2.2V and is rated for 25 mA, then you're correct that a 120 Ohm resistor should be OK. It's theoretically calculated as the voltage across the resistor divided by the desired current in the LED. (In practice, it's often more complicated than that, but that's a good starting point.)</p> <p>It's important to note that not all LEDs are rated the same though. I imagine the 220 Ohm resistor was selected for the tutorial to provide a bit of a safety margin, as that should be OK for most LEDs a hobbyist is likely to use. If you don't have access to the full specifications then it's probably better to under-drive it. The LED might be a little dim, but at least it's unlikely to be destroyed.</p> <p>Here's a useful online tool for calculating theoretical resistor values for one or more LEDs:</p> <ul> <li><a href="http://led.linear1.org/led.wiz" rel="nofollow">http://led.linear1.org/led.wiz</a></li> </ul> <p>For other devices, the resistor values required can depend on a huge number of factors. The best thing to do is to check the datasheets. For some components (such as ICs), you'll often find an "Applications" section towards the back which shows various ways you might want to connect the item to an external circuit. If things like capacitors and resistors are required, it will often explain how to select the correct ones for a given situation.</p>
5072
|usb|attiny|bootloader|
ATtiny85. How do I burn a bootloader? What is the process?
2014-10-20T19:23:45.320
<p>I want to use all six I/O pins of an ATtiny85, that means also using the reset pin as an I/O pin, however, I found out that if I disable the RESET pin, I can no longer program the ATtiny using an ISP programmer.</p> <p>However, I found out that there are bootloaders for ATtiny which, as far as I understand, allow me to program the ATtiny through USB, without the need of the RESET pin.</p> <p><strong>My question is</strong>: How do I burn such a bootloader (such as <a href="https://github.com/micronucleus/micronucleus" rel="noreferrer">micronucleus</a> for example) to the ATtiny85? And how do I need to connect the ATtiny to USB after that (like <a href="http://littlewire.cc/downloads.html" rel="noreferrer">this?</a>)? How do I program it after that? Keep in mind that in terms of burning bootloaders and modifying fuses, I am a complete newbie.</p> <p>Also, I'm using the ArduinoISP sketch as my ISP programmer since I don't have a real ISP programmer, but as far as I read, that won't be a problem.</p> <p>EDIT: I do have this thing I bought for a couple dollars on eBay, which I don't know how and if I need to to use: <img src="https://i.stack.imgur.com/5U8Nr.jpg" alt="enter image description here"></p>
<blockquote> <p>I do have this thing I bought for a couple dollars on eBay, which I don't know how and if I need to to use: </p> </blockquote> <p>it is infinitely better than your arduinoisp.</p> <p>google avrdude / avrdudess.</p>
5074
|arduino-mega|isp|atmel-studio|
How do I change fuse bits - not communicating?
2014-11-20T08:35:24.137
<p>Currently I'm working on a project using an <a href="http://www.tme.eu/en/details/mikroe-229/atmel-development-kits/mikroelektronika/mcu-card-atmega2560/#" rel="nofollow noreferrer">ATmega 2560 microcontroller card</a> with a 10&nbsp;MHz crystal. My main goal is to use the Arduino IDE to upload sketches to this chip to run my bread board circuit. In the beginning I had planned to use Atmel Studio to upload Arduino Sketches, but I decided to go with the more direct route. I am using two programmers, the Atmel ICE, and the Atmel AVR ISP MKii.</p> <p>Anyway, here is my issue. I tried to use the Arduino IDE and the MKii to burn the bootloader to the chip. However, it did not work. It uploaded, but I was at that point no longer able to communicate with the device. When I switched to Atmel Studio, and used the ICE programmer, my chip could not be read and recognized (whereas before it could). I can't even program it. (I had bought two.)</p> <p>I then figured I would try and read the fuse bits on the other programmer and burn the bootloader using Atmel Studio (since the Arduino IDE has no information on this), and I looked up <a href="http://www.avr-developers.com/bootloaderdocs/index.html" rel="nofollow noreferrer">the proper bits to change</a> and then burned the bootloader. It worked fine, and I then changed the fuse bits which resulted in an error and now I again could talk to the device.</p> <p>I am guessing that something is going wrong with the suggested fuse bits, but I do not know how to change them or how to fix this. The original fuse bits that I read from the device are listed below (before I messed it up).</p> <p>I checked my wiring a billion times and it is all perfect. I just need suggestions to fix this mess, thanks.</p> <pre><code>BODLEVEL = DISABLED OCDEN = [ ] JTAGEN = [X] SPIEN = [X] WDTON = [ ] EESAVE = [ ] BOOTSZ = 4096W_1F000 BOOTRST = [X] CKDIV8 = [ ] CKOUT = [ ] SUT_CKSEL = INTRCOSC_6CK_0MS EXTENDED = 0xFF (valid) HIGH = 0x98 (valid) LOW = 0xC2 (valid) LB = NO_LOCK BLB0 = NO_LOCK BLB1 = NO_LOCK LOCKBIT = 0xFF (valid) Detected device Device name ATmega2560 Device signature 0x1E9801 </code></pre>
<p>If AVR is bricked because of wrong fuses I suppose it's typically non-working external oscillator you need provide signal to particular AVR pin to get programmer working again. Thread related to unbricking <a href="http://www.avrfreaks.net/forum/locked-out-atmega-328p-possible-clocklow-fuse-byte-issue" rel="nofollow">http://www.avrfreaks.net/forum/locked-out-atmega-328p-possible-clocklow-fuse-byte-issue</a>.</p>
5079
|led|lcd|
Change the backlight of 2x16 LCD
2014-11-20T13:06:55.613
<p>Today I ordered a 2x16 character LCD with white characters on black background. </p> <p>Now I am wondering if I can change the backlight LED, which I guess is white for the characters, with a RGB LED to change the character color. </p> <p>Did anyone do this before? Is it even possible that way? </p> <p>I've seen RGB negative LCDs from Adafruit and Sparkfun.</p>
<p>The backlight led (<a href="http://www.adafruit.com/product/1622" rel="nofollow">sample</a>) is just a simple led with a large transparent panel, the size of the lcd, attached to it. This panel is diffused on the top in such a way that it distributes the light evenly. If you get a rgb led, file the top flat, and glue it to the side of this panel (where the leads get out of the plastic) you should get a pretty good effect.</p> <p>I tested it on my white-on-blue lcd, by holding and led to the side of this panel, and it worked. Just note that you need a very bright led. Mine was pretty bright but the letters didn't light up that much.</p>
5082
|usb|communication|ftdi|
How to connect Arduino Pro Mini with PC?
2014-11-20T15:41:14.250
<p>I'm about to buy Arduino Pro Mini (<a href="http://arduino.cc/en/Main/ArduinoBoardProMini" rel="nofollow">http://arduino.cc/en/Main/ArduinoBoardProMini</a>). As far as I can see it requires FTDI or similar circuit to program it.</p> <p>Should FTDI be present for communication with PC after sketch is uploaded to chip or there is a way to connect Arduino Pro Mini DIRECTLY to USB cable and PC?</p> <p>Is this also case with Arduino Pro Micro? (<a href="https://www.sparkfun.com/products/12640" rel="nofollow">https://www.sparkfun.com/products/12640</a>)</p> <p>Thanks in advance Petar</p>
<p>The "Arduino Pro Micro" has its own USB interface so you don't need extra stuff for it to work. However, a number of existing libraries that deals with Arduino shields do not support the new chip inside the Arduino Pro Micro (ATmega32U4) so check first to make sure it will work with what you need.</p> <p>For the "Arduino Pro Mini" (which I use a lot since it is very very cheap, about $3 from ebay) to program it I use "USPASP" (also cheap ~$3) so I have three of them but you only need one to program as many Pro Minis as you like. And for communication I use a "USB to TTL UART" (based on the "CP2102" chip which works with Linux, Windows and Mac) they are also super cheap (about $2) and you connect it to the serial pins on your Pro Mini. </p> <p>(Just search ebay for the terms I put in quotes and you will find many of them at low prices, they ship from china so it will take about a month to get to you which is why I ordered more than I need for future projects, or for a little extra you might find local sellers with same products)</p>
5083
|programming|sd-card|memory-usage|code-optimization|
releasing memory in sub-function
2014-11-20T15:49:42.547
<p>I'm doing a program who get a line from the SD and shows it, this function is called <em>getData()</em></p> <p>FULL CODE:</p> <pre><code>#include &lt;SD.h&gt; #include &lt;MemoryFree.h&gt; File myFile; int stringIndex = 0; int cursorPosition = 0; char inputString [25]; char inputChar; boolean endOfLine; char fullPath[11]; void setup(){ Serial.begin(9600); Serial.print("Initializing SD card."); pinMode(10, OUTPUT); digitalWrite(10, HIGH); if (!SD.begin(4)) { Serial.println("initialization failed!"); return; } Serial.println("initialization done."); } void loop(){ Serial.println(getDataSD()); Serial.print("freeMemory()="); Serial.println(freeMemory()); } String getDataSD(){ memset(inputString, 0, sizeof(inputString)); getFileNameSD(); myFile = SD.open(fullPath); if(myFile){ myFile.seek(cursorPosition); endOfLine = false; while(myFile.available() &amp;&amp; endOfLine == false){ inputChar = myFile.read(); if(inputChar == '*'){ while(inputChar != '\n'){ inputChar = myFile.read(); } }else{ cursorPosition = myFile.position()-1; if(inputChar == 10 || inputChar == ' ') inputChar = myFile.read(); while(inputChar != '\n'){ if(stringIndex &lt; 25){ inputString[stringIndex] = inputChar; stringIndex++; inputChar = myFile.read(); } } inputString[stringIndex-1] = '\0'; stringIndex = 0; endOfLine = true; } } myFile.close(); } return inputString; } void getFileNameSD (){ char folder[] = "/ACC"; checkFolderSD(folder); myFile = SD.open(folder); myFile = myFile.openNextFile(); if(!myFile) myFile.rewindDirectory(); if(myFile){ strcpy(fullPath,folder); strcat(fullPath,"/"); strcat(fullPath,myFile.name()); myFile.close(); } } </code></pre> <p>I don't have problem with this function(getDataSD). To get the name of the file, I've created another function who looks for a file in a specific folder, this function is called <em>getFileNameSD()</em></p> <p>I'm having problem with this last function, it's not releasing or overwriting some data, so every time it's called, it is stored new data in memory</p> <p>I've included the <a href="http://github.com/maniacbug/MemoryFree" rel="nofollow">memory Free library</a> to see where is the problem. When I call the <em>getDataSD</em> and write the file manually I dont have problem.</p> <pre><code>myFile = SD.open("/ACC/11001"); </code></pre> <p>Serial monitor</p> <pre><code>freeMemory()=6592 /-27/-26/-56/ freeMemory()=6592 /-27/-26/-56/ freeMemory()=6592 /-27/-26/-56/ freeMemory()=6592 /-27/-26/-56/ freeMemory()=6592 /-27/-26/-56/ freeMemory()=6592 /-27/-26/-56/ </code></pre> <p>the memory always is the same.</p> <p>but not when I call the <em>getFileNameSD()</em> </p> <pre><code>myFile = SD.open(getFileNameSD()); </code></pre> <p>Serial monitor</p> <pre><code>freeMemory()=6571 /-27/-26/-56/ freeMemory()=6540 /-27/-26/-56/ freeMemory()=6509 /-27/-26/-56/ freeMemory()=6478 /-27/-26/-56/ freeMemory()=6447 /-27/-26/-56/ </code></pre> <p>I know I'm doing something wrong with <em>getFileName()</em> but I don't know what is, can anybody help/explain me?</p>
<p>Well, finally someone found where was the problem. In the <em>getFileName()</em> function, I open two instances of the file but I close just one.</p> <p>here is the answer:</p> <pre><code>#include &lt;SD.h&gt; #include &lt;MemoryFree.h&gt; File myFile; int stringIndex = 0; int cursorPosition = 0; char inputString [25]; char inputChar; boolean endOfLine; char fullPath[11]; void setup(){ Serial.begin(9600); Serial.print("Initializing SD card."); pinMode(10, OUTPUT); digitalWrite(10, HIGH); if (!SD.begin(4)) { Serial.println("initialization failed!"); return; } Serial.println("initialization done."); } void loop(){ Serial.println(getDataSD()); Serial.print("freeMemory()="); Serial.println(freeMemory()); } void getDataSD(){ memset(inputString, 0, sizeof(inputString)); getFileNameSD(); myFile = SD.open(fullPath); if(myFile){ myFile.seek(cursorPosition); endOfLine = false; while(myFile.available() &amp;&amp; endOfLine == false){ inputChar = myFile.read(); if(inputChar == '*'){ while(inputChar != '\n'){ inputChar = myFile.read(); } }else{ cursorPosition = myFile.position()-1; if(inputChar == 10 || inputChar == ' ') inputChar = myFile.read(); while(inputChar != '\n'){ if(stringIndex &lt; 25){ inputString[stringIndex] = inputChar; stringIndex++; inputChar = myFile.read(); } } inputString[stringIndex-1] = '\0'; stringIndex = 0; endOfLine = true; } } myFile.close(); } } void getFileNameSD (){ char folder[] = "/ACC"; File myDir = SD.open(folder); memset(fullPath, 0, sizeof(fullPath)); if (myDir){ myFile = myDir.openNextFile(); if(myFile){ strcpy(fullPath,folder); strcat(fullPath,"/"); strcat(fullPath,myFile.name()); myFile.close(); myDir.close(); }else{ // Handle file not found myDir.close(); fullPath[0] = '0'; } }else{ // Handle directory not opened fullPath[0] = '0'; } } </code></pre>
5090
|serial|python|float|
Sending a floating point number from python to arduino
2014-11-20T20:19:41.760
<p>I am trying to send a floating point number from a python script to an Arduino. I am not sure how to do this, especially in a pythonic way.</p> <p>A little bit of research brought me to this very similar question: <a href="https://arduino.stackexchange.com/questions/3753/how-to-send-numbers-to-arduino-uno-via-python-3-and-the-module-serial">How to send numbers to Arduino UNO via Python 3 and the module serial</a> I vaguely understand why this would work for an int but don't know how to modify it.</p> <p>1) In this question it makes sense to convert to a char, send, and then convert back to a int by casting on the Arduino, I can't think how to do that for a float.</p> <p>2) Why do they convert to a Char anyway?</p> <p>3) What code do I run on the arduino to get this back into a float?</p> <p>4) Can I use bitwise operators on floating point numbers?</p> <p>I'm new to python and also to low level programming. I am also aware that python and low level don't mix to well. I am using Linux but ideally I need a cross platform solution. Although I would prefer to get it working then worry about cross platform later.</p>
<p>Floating point numbers are (should) be stored in <a href="https://en.wikipedia.org/wiki/IEEE_floating_point" rel="nofollow">IEEE 754 format</a>.</p> <p>If you simply write the binary bytes of a floating point number down the serial line, it should be possible to unpack them at the other end.</p> <p>To do this (Arduino C/C++), make a pointer from your variable, by casting the address of it to char*. Void* would probably work too.</p> <pre><code> float my_value = 22.812; my_port.write((const char *)&amp;my_value, sizeof(float)/*4*/); </code></pre> <p>And the unpacking - there's a few ways to do this, but I like:</p> <pre><code> float incoming_value; unsigned char buffer[4]; // If we read enough bytes, unpacked it if (my_serial.readBytes(buffer, sizeof(float)) == sizeof(float)) memcpy(&amp;incoming_value, buffer, sizeof(float)); else // I/O error - no data, not enough bytes, etc. incoming_value = 0 </code></pre> <p>On the other end (python), bytes are best handled with the <strong>struct</strong> module. This will handle the packing and unpacking for you.</p> <pre><code>import struct ... try: ieee754_data = my_serial.read(4) my_float = struct.unpack('f', ieee754_data) catch: # I/O Error, or junk data my_float = 0.0 </code></pre> <p>And packing:</p> <pre><code> ieee754_data = struct.pack('f', my_float) try: my_serial.write(ieee754_data) catch: pass #TODO - I/O Error </code></pre> <p>One more note - You might consider using doubles instead of floats for extra precision. Python floats have the precision of a C/C++ double already.</p>
5092
|i2c|attiny|
Ideas for setting I2C device IDs
2014-11-20T21:33:05.793
<p>I am using I2C to communicate between a collection of ATtiny85s that are acting as controllers for various parts of a system and the "Main Brain" -- a RaspberryPi. Most of the ATtiny85s only have a couple of free pins left (usually Pins 1 and 2 -- the reset and the pin that can't be used for PWM) so I can't use something like a DIP switch to directly set device IDs. I'd rather not hardcode the device IDs when I push code to the tinys but I can't think of a good, simple, and reliable way to do it otherwise. Anyone here have a suggestion?</p>
<p>Put the address in EEPROM. It's still "on the chip" but it can be programmed independent of the flash, and can be changed on the fly if deemed appropriate.</p>
5097
|spi|
How do I transfer more than 1 byte at once via SPI bus?
2014-11-20T18:14:48.210
<p>I have an <a href="http://www.analog.com/static/imported-files/data_sheets/AD5686R_5685R_5684R.pdf" rel="noreferrer">AD5685R DAC</a> that I am trying to communicate with over SPI. Per the datasheet,</p> <blockquote> <p>...These [24] bits are transferred to the input register on the 24 falling edges of <code>SCLK</code> and are updated on the rising edge of <code>/SYNC</code></p> </blockquote> <p>where <code>/SYNC</code> is used as chip-select.</p> <p>I believe Arduino's <a href="http://arduino.cc/en/Reference/SPITransfer" rel="noreferrer"><code>SPI.transfer</code></a> waits to receive 8 bits after sending 8 bits. But for this particular DAC, I need to send 24 straight bits on 24 clock edges before releasing the chip-select. Is this possible?</p>
<p>Note that there is also a version of <a href="https://www.arduino.cc/en/Reference/SPITransfer" rel="noreferrer"><code>SPI.transfer</code></a> for multi-byte (buffer) transfers:</p> <pre><code>SPI.transfer(buffer, size) </code></pre> <p>I used the buffer transfer in my <a href="https://github.com/ulrichstern/Tlc59711/wiki" rel="noreferrer">library</a> for the TLC59711 (see <a href="https://github.com/ulrichstern/Tlc59711/blob/v1.0.1/Tlc59711.cpp#L91" rel="noreferrer">code</a>) and found the buffer transfer faster than transferring bytes individually using <code>SPI.transfer(val)</code>; the switch to buffer transfers is <em>one</em> of the reasons my library is about 3.5 times faster than a previous library for the TLC59711.</p>
5106
|arduino-mega|led|
Why doesn't pin 9 blink?
2014-11-21T09:40:41.107
<p>I use simple LED blinking code on an <a href="https://www.arduino.cc/en/Main/ArduinoBoardMega2560" rel="nofollow noreferrer">Arduino MEGA 2560</a>. I simulate it in Proteus. But pin number 9 doesn't power up. What is the problem?</p> <p>My code:</p> <pre><code>// Set up the DATA direction void setup() { for(int i = 1; i&lt;9; i++) pinMode (i, OUTPUT); } // The main program void loop() { for(int j=2; j&lt;=10; j++) { digitalWrite(j, HIGH); delay(100); digitalWrite(j, LOW); } for(int j=9; j&gt;=2; j--) { digitalWrite(j, HIGH); delay(100); digitalWrite(j, LOW); } } </code></pre> <p>And the circuit is:</p> <p><img src="https://i.stack.imgur.com/DeHzm.png" alt="Enter image description here"></p>
<p>It looks like your main problem is the loop in <code>setup()</code>:</p> <pre><code>for(int i = 1; i&lt;9; i++) pinMode (i, OUTPUT); </code></pre> <p>This will call <code>pinMode()</code> with values 1 to 8 (inclusive), and then stop. That means you aren't configuring pin 9 as an output. You need to change the loop condition to <strong><code>i&lt;=9</code></strong>.</p> <p>However, if your circuit diagram is accurate then you will have another problem. When implementing the circuit for real, you absolutely <strong>must</strong> have a suitable resistor in series with each LED (maybe something around 200 Ohms, depending on the exact specifications). If not, you seriously risk destroying the LEDs and maybe damaging your Arduino.</p>
5111
|ir|
Why is resolution 20?
2014-11-21T19:35:12.353
<p>I am using an amazing code to send/read infrared pulses without any external library. The code is fine and I took about 1 hour to fully understand it. The only thing I didnt understand is the variable RESOLUTION. I believe it should be 0 not 20. I think it should be as low as possible.</p> <p>You can see the code at:</p> <p><a href="https://learn.adafruit.com/ir-sensor/using-an-ir-sensor" rel="nofollow noreferrer">https://learn.adafruit.com/ir-sensor/using-an-ir-sensor</a></p> <p>or below:</p> <pre><code>/* Raw IR decoder sketch! This sketch/program uses the Arduino and a PNA4602 to decode IR received. This can be used to make a IR receiver (by looking for a particular code) or transmitter (by pulsing an IR LED at ~38KHz for the durations detected Code is public domain, check out www.ladyada.net and adafruit.com for more tutorials! */ // We need to use the 'raw' pin reading methods // because timing is very important here and the digitalRead() // procedure is slower! //uint8_t IRpin = 2; // Digital pin #2 is the same as Pin D2 see // http://arduino.cc/en/Hacking/PinMapping168 for the 'raw' pin mapping #define IRpin_PIN PIND #define IRpin 2 // for MEGA use these! //#define IRpin_PIN PINE //#define IRpin 4 // the maximum pulse we'll listen for - 65 milliseconds is a long time #define MAXPULSE 65000 // what our timing resolution should be, larger is better // as its more 'precise' - but too large and you wont get // accurate timing #define RESOLUTION 20 // we will store up to 100 pulse pairs (this is -a lot-) uint16_t pulses[100][2]; // pair is high and low pulse uint8_t currentpulse = 0; // index for pulses we're storing void setup(void) { Serial.begin(9600); Serial.println("Ready to decode IR!"); } void loop(void) { uint16_t highpulse, lowpulse; // temporary storage timing highpulse = lowpulse = 0; // start out with no pulse length // while (digitalRead(IRpin)) { // this is too slow! while (IRpin_PIN &amp; (1 &lt;&lt; IRpin)) { // pin is still HIGH // count off another few microseconds highpulse++; delayMicroseconds(RESOLUTION); // If the pulse is too long, we 'timed out' - either nothing // was received or the code is finished, so print what // we've grabbed so far, and then reset if ((highpulse &gt;= MAXPULSE) &amp;&amp; (currentpulse != 0)) { printpulses(); currentpulse=0; return; } } // we didn't time out so lets stash the reading pulses[currentpulse][0] = highpulse; // same as above while (! (IRpin_PIN &amp; _BV(IRpin))) { // pin is still LOW lowpulse++; delayMicroseconds(RESOLUTION); if ((lowpulse &gt;= MAXPULSE) &amp;&amp; (currentpulse != 0)) { printpulses(); currentpulse=0; return; } } pulses[currentpulse][1] = lowpulse; // we read one high-low pulse successfully, continue! currentpulse++; } void printpulses(void) { Serial.println("\n\r\n\rReceived: \n\rOFF \tON"); for (uint8_t i = 0; i &lt; currentpulse; i++) { Serial.print(pulses * RESOLUTION, DEC); Serial.print(" usec, "); Serial.print(pulses[1] * RESOLUTION, DEC); Serial.println(" usec"); } // print it in a 'array' format Serial.println("int IRsignal[] = {"); Serial.println("// ON, OFF (in 10's of microseconds)"); for (uint8_t i = 0; i &lt; currentpulse-1; i++) { Serial.print("\t"); // tab Serial.print(pulses[1] * RESOLUTION / 10, DEC); Serial.print(", "); Serial.print(pulses[i+1][0] * RESOLUTION / 10, DEC); Serial.println(","); } Serial.print("\t"); // tab Serial.print(pulses[currentpulse-1][1] * RESOLUTION / 10, DEC); Serial.print(", 0};"); } </code></pre>
<p>Most IR remotes send pulses that are at least 400 micro seconds long. E.g. on a NEC IR remote you get pulses that are 560 or 2240 microseconds long (depending on whether it's sending a 1 or a 0). </p> <p>So with a RESOLUTION of 20 you get at least 20 'pulse counts' for a <code>0</code> and 80 for a <code>1</code>. Because remotes aren't that precise in you'll get somewhere between e.g. 18 and 22 or 78 and 82. Those values are different enough to easily detect whether a 0 or 1 was send. </p> <p>Changing this RESOLUTION to e.g. 2 will give you 200 or 800 pulsecounts. You'll get a more precise timings from a still imprecise source. But this better precision is useless.</p> <p>PS setting it to 0 could break the code, as the highpulse and lowpulse are only 16 bit integers so they will overflow after 65536, which will happen pretty fast.</p> <p>Hope that helps somewhat. Just let me know is anything is still unclear.</p>
5112
|ir|
How this smal infrared work
2014-11-21T19:46:23.093
<p>I have a code that sends 384 pulses at 38kHz with an infrared LED. It's very easy to understand it. At the beggining the code sends the pulses using the LED and in the middle of the code I check the sensor if it has any signal coming. So far so good, yes? Please, take a look:</p> <pre><code>for(int i=0;i&lt;384;i++) { digitalWrite(IRledPin,HIGH); delayMicroseconds(13); digitalWrite(IRledPin,LOW); delayMicroseconds(13); } if (digitalRead(IRsensorPin) == LOW){ digitalWrite(D13ledPin,HIGH); } else { digitalWrite(D13ledPin,LOW); } </code></pre> <p>My question is this: I first send the pulses, so when I reach the line <code>if (digitalRead(IRsensorPin) == LOW){</code> the pulse should already have passed the sensor. So why does it work? It should not work cause I first send the pulse and then I check for the pulse but as I understand the 384 pulses should already have passed the sensor.</p> <p>I have no idea why this code works. I would be glad to listen smarter people to help me understand this.</p> <p>Thank you.</p>
<p>The IR receiver does some filtering on the signal. It doesn't signal a LOW immediately if it lost a single pulse of light. A speck of dust, hanging in the air, might just be blocking the IR phototransitor. Or some brief flash of light, making two pulses seem like one or more.</p> <p>These IR receivers a specifically build to filter out the 'noise' coming from other light sources and light obstructions.</p> <p>Identically, you would want this receiver to give you a HIGH if it detect only 2 pulses of light 13uS apart. I could just be some sunlight reflected from a puddle, accidentally matching 38kHz.</p>
5118
|arduino-uno|
Lessons 2: Spaceship interface
2014-11-22T10:47:10.340
<p>I'm just starting to discover Arduino. Currently, I've done 2 lessons from Arduino book and I have few questions about second circuit. <img src="https://i.stack.imgur.com/QfxUh.jpg" alt="schema of second circuit"></p> <ol> <li>Why we need to add 10kOm resistors after wire to 2 pin?</li> <li>Why we need to add resistors after LED?</li> <li>And why 3, 5, 6, 9, 10, 11 pins with "wave" symbol?</li> </ol>
<blockquote> <p>Why we need to add 10kOm resistors after wire to 2 pin?</p> </blockquote> <p>Due to some weird electronic properties, the state of the input to the Arduino is "undefined" when there is nothing connected. When the button isn't pressed down, it is neither connected to 5V or GND; it is left <em>floating</em>. When floating, the input isn't reliable.</p> <p>To make sure that the input always has some sort of signal, we connect it to ground. However, there is a problem with directly connecting the input to ground. When you would push the button, you would create a short circuit by allowing current to flow directly from 5V to GND without any current limiting.</p> <p>The solution is to add a resistor to limit the current between 5V and GND. When the button isn't pushed, the input is grounded to allow it to read LOW. When the button is pushed, the 5V rushes in and, since the 5V doesn't use a resistor, "the 5V is stronger," making the input HIGH.</p> <blockquote> <p>Why we need to add resistors after LED?</p> </blockquote> <p>An overly simplified explanation: A LED will theoretically pull infinite power (as current) from your power source without a resistor. With too much power, the LED will be destroyed from heat.</p> <p>Because the LED has <em>some</em> resistance, it will pull up to a finite amount of power, but that usually is much more than the LED can handle (and sometimes what the power supply can supply). We need a resistor there to ensure that the LED can only draw as much power as it can handle.</p> <blockquote> <p>And why 3, 5, 6, 9, 10, 11 pins with "wave" symbol?</p> </blockquote> <p>If you look at an Arduino board, it will say <code>DIGITAL (PWM~)</code>. That <code>(PWM~)</code> means that any pins with the "~" symbol are <em>PWM</em> pins... pins that can turn on and off their output very fast, in this case to create an illusion that the LED is dimming because the state changes faster than the human eye can detect.</p> <blockquote> <p><img src="https://i.stack.imgur.com/8eLah.jpg" alt="Arduino Uno"> <em><a href="http://arduino.cc/en/uploads/Main/ArduinoUnoFront240.jpg" rel="nofollow noreferrer">http://arduino.cc/en/uploads/Main/ArduinoUnoFront240.jpg</a></em></p> </blockquote> <p>More explanation for PWM here: <a href="http://arduino.cc/en/Tutorial/PWM" rel="nofollow noreferrer">Arduino docs</a>, <a href="https://electronics.stackexchange.com/questions/67116/why-do-some-pins-have-signs-next-to-their-numbers">an answer [of mine]</a></p>
5119
|serial|arduino-nano|usb|mac-os|
Arduino Nano no serial port for MacBook Air 2013
2014-11-22T11:59:04.293
<h1>Problem</h1> <p>I have an Arduino Nano connected via a USB cable (Type A to Mini Type B) to my MacBook Air (Mid 2013 Model). The PWR LED is on while the arduino is connected. </p> <p>Opening the Arduino software, pulling down the <code>Tools &gt; Serial Port</code> menu does not show me a valid serial port. All I see is:</p> <pre><code>/dev/tty.Bluetooth-Incoming-Port /dev/cu.Bluetooth-Incoming-Port /dev/tty.Bluetooth-Modem /dev/cu.Bluetooth-Modem </code></pre> <h2>What I've tried and did not work</h2> <ul> <li><p>I have installed the correct FTDI driver (v2.2.18). x64 for my MacBook Air's Corei5, file <code>FTDIUSBSerialDriver_10_4_10_5_10_6_10_7.mpkg</code>. Restarted after installation.</p></li> <li><p>Tried connecting arduino to both USB ports on my Air.</p></li> </ul> <h2>More Info</h2> <ul> <li>Running Mac OSX 10.10 Yosemite</li> <li>Same arduino and cable work when connected to a Windows machine or a Raspberry Pi.</li> </ul> <p>If it helps, I can see the USB Serial in my <code>Apple Logo &gt; About This Mac &gt; System Report</code> under <code>Hardware &gt; USB</code></p> <pre><code>USB2.0-Serial: Product ID: 0x7523 Vendor ID: 0x1a86 Version: 2.54 Speed: Up to 12 Mb/sec Location ID: 0x14100000 / 8 Current Available (mA): 500 Current Required (mA): Unknown (Device has not been configured) </code></pre> <p>I'm out of ideas and options. Any help would be greatly appreciated.</p> <p>Thanks in advance :)</p>
<p>This solved it for me.</p> <ul> <li>Download <a href="http://www.wch.cn/downloads.php?name=pro&amp;proid=178" rel="nofollow">this driver</a></li> <li>Install it</li> <li>Run <code>sudo nvram boot-args="kext-dev-mode=1"</code></li> <li>Reboot</li> </ul> <p>Serial ports now showed up in the Arduino IDE and also when I used <code>ls -1 /dev/tty*</code></p> <p>Hopes this helps someone.</p> <p>Reference: <a href="http://forum.arduino.cc/index.php?topic=261375.0" rel="nofollow">This thread</a></p>
5125
|programming|led|time|
Delay not working in function other than loop
2014-11-22T15:59:18.623
<p>So I just got an Arduino and thought I would play around a bit.</p> <p>However not five minutes in I already ran into a problem.</p> <p>I tried programming a simple SOS blinking light sequence. To get rid of code duplication I refactored the on and off turning of the LED into functions and then again refactored a short blink and a long blink function which are expected to turn the LED on for a short time and then for a long time.</p> <p>The problem is the delay in those functions is completely ignored. </p> <pre><code>int ledPin = 13; void on() { digitalWrite(ledPin,HIGH); } void off() { digitalWrite(ledPin,LOW); } void shortB() { on(); delay(1000); off(); } void longB() { on(); delay(2000); off(); } void setup() { pinMode(ledPin, OUTPUT); } void loop() { shortB(); shortB(); shortB(); shortB(); longB(); longB(); longB(); shortB(); shortB(); shortB(); delay(5000); } </code></pre> <p>My expected behavior would be that it does an SOS and then waits 5 seconds and repeats.</p> <p>What really happens however is that it stay continuously lit for a second or so then turns off for 5 seconds.</p> <p>Using </p> <pre><code>on(); delay(1000); off(); </code></pre> <p>In the main loop works so I guess it simply ignores the delays that are put into the other functions. My question would be why and ho do I fix it?</p> <p>I know that I can use other timer function constructs however I really think this is something that should work by default.</p>
<p>In addition to the other problems, you should have a break between <strong>letters</strong>. So, for example, "S" is not just dot-dot-dot it is dot-dot-dot-pause.</p> <p>Example code below that implements pauses between letters, as well as longer pauses between words.</p> <pre class="lang-C++ prettyprint-override"><code>const byte LED = 13; char * letters [26] = { ".-", // A "-...", // B "-.-.", // C "-..", // D ".", // E "..-.", // F "--.", // G "....", // H "..", // I ".---", // J "-.-", // K ".-..", // L "--", // M "-.", // N "---", // O ".--.", // P "--.-", // Q ".-.", // R "...", // S "-", // T "..-", // U "...-", // V ".--", // W "-..-", // X "-.--", // Y "--.." // Z }; char * numbers [10] = { "-----", // 0 ".----", // 1 "..---", // 2 "...--", // 3 "....-", // 4 ".....", // 5 "-....", // 6 "--...", // 7 "---..", // 8 "----.", // 9 }; const unsigned long dotLength = 100; // mS const unsigned long dashLength = dotLength * 3; const unsigned long wordLength = dashLength * 2; // get a line from serial // forces to upper case void getline (char * buf, size_t bufsize) { byte i; // discard any old junk while (Serial.available ()) Serial.read (); for (i = 0; i &lt; bufsize - 1; ) { if (Serial.available ()) { int c = Serial.read (); if (c == '\n') // newline terminates break; buf [i++] = toupper (c); } // end if available } // end of for buf [i] = 0; // terminator Serial.println (buf); // echo what they typed } // end of getline void dot () { digitalWrite (LED, HIGH); delay (dotLength); digitalWrite (LED, LOW); delay (dotLength); } // end of dot void dash () { digitalWrite (LED, HIGH); delay (dashLength); digitalWrite (LED, LOW); delay (dotLength); } // end of dash void setup () { Serial.begin (115200); Serial.println (); pinMode (LED, OUTPUT); } // end of setup void loop () { Serial.println ("Enter your message ..."); char buf [60]; getline (buf, sizeof buf); // for each letter for (char * p = buf; *p; p++) { char c = *p; char * sequence = NULL; if (c &gt;= 'A' &amp;&amp; c &lt;= 'Z') sequence = letters [c - 'A']; else if (c &gt;= '0' &amp;&amp; c &lt;= '9') sequence = numbers [c - '0']; else if (c == ' ') { delay (wordLength); // gap between words continue; } // ignore not in table if (sequence == NULL) continue; // output sequence for one letter for (char * s = sequence; *s; s++) { if (*s == '.') dot (); else if (*s == '-') dash (); } // now a gap delay (dashLength); } // end of for each letter } // end of loop </code></pre>
5127
|current|resistor|
How much current and voltage has my resistor + LED
2014-11-22T16:21:56.487
<p>I have a very simple circuit: 5v -> LED (5mm, forward voltage of 2 V and max. current of 20mA) -> 1k ohm resistor -> GND.</p> <p>I want to know how much current is flowing in my circuit. I am using this formula:</p> <p>U = R x I</p> <p>Since U = 5, and R = 1000 the current is (according to the formula): 5/1000 = 0.005A.</p> <p>So far so good. The problem is when I try to check the voltage drop over the resistor and the LED. For calculating the voltage drop in the resistor I would use the same formula where I is my current (0.005A) and R is the resistor 1k ohm. The result is: 5 V. </p> <p>Something very weird is happening here cause the voltage drop around my resistor should not be 5 V cause I know there must be another voltage drop around the LED. If 5V is in the resistor it would mean that 0v is around the LED (and it should not light up but it does).</p> <p>Thank you helping me with this basic calculus.</p>
<p>The problem is that if you're trying to measure the current directly, you're going to get the wrong answer. Whether it's due to burden voltage or the (in)accuracy of the meter, it's a hopeless situation. The 0.005A your meter is showing is actually closer to 3mA in reality, but your meter can't distinguish between the two well enough.</p> <p>If you need to measure current this small then the only way to do so accurately is to use a very low-value shunt resistor and an amplifier. This is the method the <a href="http://www.eevblog.com/projects/ucurrent/" rel="nofollow">µCurrent</a> uses, and it's essentially the defacto gold standard for measuring current in small circuits.</p>
5129
|led|resistor|
Source power with 2 V and LED with forward voltage of 2 V
2014-11-22T16:50:56.007
<p>I have a source power with 2 V and 100mA. I have an LED that has a forward voltage of 2 V and a max current of 20mA.</p> <p>Should I use a resistor to reduce the current? I see many formulas in the internet saying the the resistor value should be:</p> <p>(Source Voltage - LED forwared voltage)/LED max current</p> <p>This formula always worked fine for me, but now that I have a 2 V source power this formula tells me that the resistor should be 0 ohm. Of course this would damage my LED cause the 100mA provided by my source power is way above the 20mA current limit of the lED.</p>
<p>No, it would not damage your led. The forward voltage of a led is, the voltage at which the led 'conducts' the maximum current it can handle. Since diodes have a (exponential) curve, the current though a diode depends on the voltage across it.</p> <p>So if you give the led 2V, it will use only 20mA. However if the voltage goes to e.g. 2.1V the current might be 25mA (since the curve is exponential), which is a bit too high, and will reduce the leds lifespan.</p> <p>So for safely I'd add some resistors. E.g. a 10Ohm resistor will limit the current to 20mA max, as long as the voltage doesn't go over 2.2V</p> <p>PS note that led Christmas lights use the same method to limit current, without a single resistor. I have here a 24v string of leds, grouped into 10 leds connected in series. So the voltage across each led is 2.4V. They are white leds, so they probably have a forward voltage of around 3.2v. But since they only get 2.4v, they will probably use only 5mA or less.</p>