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
|
---|---|---|---|---|---|
13334 | |arduino-yun| | Change arduino.local server address | 2015-07-10T08:17:55.603 | <p>I have a Yun and I'm trying to change the URL I type in to access the Web UI.</p>
<p>I've successfully changed its hostname in <code>/etc/config/system</code>, which now lets me SSH in using the new name. However:</p>
<ul>
<li>Going to newname.local doesn't work (no response at all).</li>
<li>Going to arduino.local pulls up the green page 'Wait a moment or click here...', after which no page is rendered.</li>
</ul>
<p>How can I access my Yun by typing in newname.local in my browser?</p>
| <p>That should be working fine.</p>
<p>I just logged into my Yún and changed its name by editing that file. I then restarted <code>avahi-daemon</code> since that is what broadcasts its name (faster to restart the daemon that reboot the whole Yún).</p>
<p>Browsing to the new name worked fine.</p>
<pre><code>matt@dell:~$ ssh root@arduino.local
root@Arduino:~# vi /etc/config/system
(edit the config file)
root@Arduino:~# hostname skybridge
(manually changing the hostname so I don't have to reboot)
root@skybridge:~# /etc/init.d/avahi-daemon restart
(restart the avahi daemon)
</code></pre>
<p>Browsing to <code>skybridge.local</code> now shows me the Arduino login as it should.</p>
<p>As a further test I have just rebooted my Yún so it runs everything from scratch and it still works fine.</p>
<p>There are a number of caches involved in the system, any of which may be getting in the way. It could be that the browser has cached incorrect or out of date information about the FQDN (<em>fully qualified domain name</em>) for the name you have given your Yún, in which case just closing and re-opening your browser may help. It may be that the mDNS lookup system on your computer (you haven't mentioned which operating system you are using, which is a big factor) has cached old or out-dated information for the FQDN, in which case flushing that cache may help (how you do that depends on your OS), or just rebooting your computer.</p>
<p>Incidentally, if you are on Linux (Windows lacks these basic networking facilities along with many other basic tools), you can query the network for your Arduino Yún with the <code>avahi-browse</code> and <code>avahi-resolve</code> commands. OS X has similar tools, but I don't know off hand what the commands are:</p>
<pre><code>matt@dell:~$ avahi-browse _arduino._tcp
+ wlan0 IPv4 skybridge _arduino._tcp local
^CGot SIGINT, quitting.
matt@dell:~$ avahi-resolve -n skybridge.local
skybridge.local 192.168.0.252
</code></pre>
|
13335 | |c++|uploading|progmem| | How do I upload sketch (and parameters) through a user interface | 2015-07-10T10:32:52.277 | <p>I'm pretty new to Arduino and I'm developing my first real-world project. </p>
<p>I have a Arduino Mega with a full working sketch in it which is going to be placed in several distant places and I have a number of "mantainers" that will need to get to the place, connect the board with their Windows (Vista+) laptop (USB), upload a new version of the sketch (if available), download some data from EEPROM and change (if needed) some parameters stored in PROGMEM. This just to give you the full picture, now I come to the questions.</p>
<p>What I'm trying to attempt is to write (in c++) a software that gives non-programmers a UI to do this stuff easily, so I wonder:</p>
<ol>
<li>How do I load the .hex file to the board? I kinda got I have to use AVRdude: is there any c++ example/tutorial/library I can use not to reinvent the wheel?</li>
<li>When can I write to PROGMEM? When I connect with the serial cable Arduino stops the running sketch, waits for a new sketch and, if it does not arrive, it starts the old sketch back again. I guess that is the time to write to PROGMEM: if there is a running sketch I cannot do it, am I right?</li>
</ol>
| <p>The avrdude/upload part has been fairly well covered by the other answers, but what has not been mentioned yet is that it is fairy trivial to modify program memory contents by modifying the hex file to be uploaded.</p>
<p>Basically, you just write hex-encoded bytes in the correct place in the file, and then update the checksum at the end of each line you modify. It can help if you put a readily recognizable placeholder sequence in the desired location in your source code, which you can look for in the hex file as an extra verification you are making your substitutions in the correct place. This is fairly straightforward string processing and unsigned byte math which you can accomplish in the language of your choice. There are also tools which can convert between hex files and binary images, and probably tools or libraries which can fix the checksums for you.</p>
<p>Do pay attention to the license terms of avrdude and any other non-original code or tools you distribute.</p>
|
13345 | |arduino-mega|arduino-ide|mac-os| | Reading Arduino from Java is way too slow | 2015-07-10T13:12:14.840 | <p>I am trying to write a simple Java program to display the analog input fed to an Arduino board upon a stimulus from a user on some physical sensors.</p>
<p>If I use the Arduino program itself and look at the serial monitor, I see the analog read based on user input updated instantly. However, when reading the input from my Java program, there is a significant delay (8-12 seconds) between the physical stimulus and the display of the value.</p>
<p>The code uploaded to Arduino is very simple, just cycle through a bunch of analog ports and print the data:</p>
<pre><code>void setup() {
Serial.begin(9600);
pinMode(30, OUTPUT);
}
void loop()
digitalWrite(30, HIGH);
for (int i = 0; i < 10; i++) {
int sensorValue = analogRead(i);
Serial.print(String(i) + ":");
Serial.println(sensorValue);
}
}
</code></pre>
<p>The Java code I am using is almost entirely copied from the example provided <a href="http://playground.arduino.cc/Interfacing/Java" rel="nofollow">here</a>, with the exception that I updated the port name to work for my system (Mac OS X 10.10.3).</p>
<p>Here is the Java code:</p>
<pre><code>import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.util.Enumeration;
public class SerialTest implements SerialPortEventListener {
SerialPort serialPort;
/** The port we're normally going to use. */
private static final String PORT_NAMES[] = {
"/dev/cu.usbmodem1411",
"/dev/cu.usbmodem1451",
};
/**
* A BufferedReader which will be fed by a InputStreamReader
* converting the bytes into characters
* making the displayed results codepage independent
*/
private BufferedReader input;
/** The output stream to the port */
private OutputStream output;
/** Milliseconds to block while waiting for port open */
private static final int TIME_OUT = 2000;
/** Default bits per second for COM port. */
private static final int DATA_RATE = 9600;
public void initialize() {
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
//First, Find an instance of serial port as set in PORT_NAMES.
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
for (String portName : PORT_NAMES) {
if (currPortId.getName().equals(portName)) {
portId = currPortId;
break;
}
}
}
if (portId == null) {
System.out.println("Could not find COM port.");
return;
}
try {
// open serial port, and use class name for the appName.
serialPort = (SerialPort) portId.open(this.getClass().getName(),
TIME_OUT);
// set port parameters
serialPort.setSerialPortParams(DATA_RATE,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
// open the streams
input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
output = serialPort.getOutputStream();
// add event listeners
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
} catch (Exception e) {
System.err.println(e.toString());
}
}
/**
* This should be called when you stop using the port.
* This will prevent port locking on platforms like Linux.
*/
public synchronized void close() {
if (serialPort != null) {
serialPort.removeEventListener();
serialPort.close();
}
}
/**
* Handle an event on the serial port. Read the data and print it.
*/
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
String inputLine=input.readLine();
System.out.println(inputLine);
} catch (Exception e) {
System.err.println(e.toString());
}
}
// Ignore all the other eventTypes, but you should consider the other ones.
}
public static void main(String[] args) throws Exception {
SerialTest main = new SerialTest();
main.initialize();
Thread t=new Thread() {
public void run() {
//the following line will keep this app alive for 1000 seconds,
//waiting for events to occur and responding to them (printing incoming messages to console).
try {Thread.sleep(1000000);} catch (InterruptedException ie) {}
}
};
t.start();
System.out.println("Started");
}
}
</code></pre>
<p>All the program does is print out the values of the Arduino serial monitor, yet it takes way longer (8-12 seconds) through Java than it does from the Arduino program itself.</p>
<p>1) Why is this happening?<br>
2) How do I fix it?</p>
| <p>One more thing you could do is create a <code>while(true)</code> loop, after <code>initialize()</code> and call <code>input.readLine()</code>, so that you don't wait for the event to appear. </p>
<p>For some reason the event is delayed, but doing the while loop hasn't created any issues or exceptions for me so far.</p>
<p>My code is like this:</p>
<pre><code>public void initialize() {
//initializing stuff
while(true){
try {
String inputLine = input.readLine();
//do stuff here
} catch (Exception e) {
System.err.println(e.toString());
}
}
}
</code></pre>
|
13347 | |arduino-uno|programming|shields|usb| | xBox receiver code output is scrambled | 2015-07-10T14:37:19.617 | <p>I'm running the following code:</p>
<pre><code>#include <XBOXRECV.h>
// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif
USB Usb;
XBOXRECV Xbox(&Usb);
void setup() {
Serial.begin(115200);
#if !defined(__MIPSEL__)
while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
if (Usb.Init() == -1) {
Serial.print(F("\r\nOSC did not start"));
while (1); //halt
}
Serial.print(F("\r\nXbox Wireless Receiver Library Started"));
}
void loop() {
Usb.Task();
if (Xbox.XboxReceiverConnected) {
if (Xbox.getAnalogHat(LeftHatY) == 0) {
Serial.print(Xbox.getAnalogHat(LeftHatY));
}
Serial.print("TEST");
}
}
</code></pre>
<p>After running the example that the library includes and a spin off I wrote for test purposes I keep getting random output, this is just some of it:</p>
<blockquote>
<p>9�]==�=�~=���y��:.�:�:����9�=��������:�:�\=���^=�?�}�:^���:�|]=9�\=<em>�</em>�������:�ܗ��.\�~=���</p>
</blockquote>
| <p>Seems like wrong baud-rate. Change baud-rate in the Arduino IDE serial monitor. </p>
|
13355 | |avrdude|isp| | Standalone Atmega 2560 ISP program | 2015-07-10T18:38:59.813 | <p>First I need to say, I'm a complete electrics newbie, so I need your help.</p>
<p>I have got a standalone Atmega 2560, which I want to program. I connected MISO, MOSI, SCK, RESET, 5V and GND to an Arduino Uno.
In addition a 16MHZ oscillator is connected to XTAL1 and XTAL2 plus I pull all VINs of the Atmega with a 100nF to GND. Plus I connected a separate VIN and GND to the 2560.</p>
<p>I programmed the Arduino Uno as an "Arduino as ISP". Afterwards I connected the 2560 as mentioned above, changed the board to "Mega 2560" and tried to upload a sketch through the Arduino and I get the error message:
avrdude: stk500v2_getsync(): timeout communicating with programmer</p>
<p>Is there something I missed?</p>
<p>Cheers
jb</p>
| <p>I have a <a href="http://www.gammon.com.au/bootloader" rel="nofollow">sketch that programs bootloaders</a>. A side-effect of that sketch is it fixes up the "divide clock by 8" fuse.</p>
<p>It looks like the wiring will be the same, but cross-check on that page (scroll down to the part about programming the Mega2560).</p>
<p>Once a bootloader is installed you could use it, if you get an FTDI cable, or simply go back to using the ArduinoISP now that the fuse is fixed.</p>
|
13364 | |voltage-level|analogread|photoresistor|voltage-protection|digital-in| | Reading a photoresistor | 2015-07-11T01:22:19.313 | <p>I have a wire with a 0-5v current. I want to detect if the current is there or not (HIGH/LOW.)</p>
<p>I'm using an optocoupler to avoid putting too much current into my micro, as it is only a 3.3V micro. I'm nervous about powering this on as one of my other micros stopped working although it's not clear if it could have been the circuit? </p>
<p><img src="https://i.stack.imgur.com/hnbMR.jpg" alt="enter image description here">
I could not find my optocoupler in fritzing. This is it:
<a href="http://rads.stackoverflow.com/amzn/click/B00CGXK1RG" rel="nofollow noreferrer">http://www.amazon.com/gp/product/B00CGXK1RG?psc=1&redirect=true&ref_=oh_aui_detailpage_o07_s00</a></p>
<p>This is my plan.</p>
<p><img src="https://i.stack.imgur.com/aUsOB.jpg" alt="The microcontroller is a spark/particle core. It the yellow wire connects to the analog/digital pin A6. The screw terminals connect to the wire with the 5v current that I'm trying to detect."></p>
<p>The microcontroller is a spark/particle core 3.3v. It the yellow wire connects to the analog pin A6. The screw terminals connect to the wire with the 5v current that I'm trying to detect.</p>
<p>I based my circuit on this:</p>
<p><img src="https://i.stack.imgur.com/sL3r6.jpg" alt="enter image description here"></p>
<p>But I don't know if it will do the same thing.</p>
<p><img src="https://i.stack.imgur.com/D1vAE.jpg" alt="enter image description here"></p>
| <p>Based on the revised information given above I present a different answer. Use the opto-coupler as shown here:</p>
<p>Your kettle LED will be in series with the optocoupler (note the polarity, not reversed like in your question).</p>
<p>If the LED is on the transistor in the PC817 will conduct and the Arduino pin will be LOW. If the LED is off the transistor will not conduct and the Arduino pin will be HIGH.</p>
<p><img src="https://i.stack.imgur.com/D14NA.png" alt="enter image description here"></p>
<p>Note: The Arduino pin will be the reverse of the kettle LED.</p>
<p>I'm leaving the other answer there because I think it is a reasonable answer to the question of "detect a voltage".</p>
|
13367 | |arduino-yun|sd-card|linux| | Does restarting Yún configuration mess up Arduino or its SD card? | 2015-07-11T03:41:13.157 | <p>I noticed something odd recently - a Yún, that was working previously, wouldn't connect.</p>
<p>After logging in to the web setup, setting the access point and password (which hadn't changed), and save & restart, it connected. Unfortunately, it still doesn't work, and after ssh into it, I find I cannot <code>ls /mnt/sd/</code> or <code>sda1</code>. It just sits there, requiring Ctrl+C, and gives no output.</p>
<p>Did I reset the Arduino or Linux somehow by setting up access point again, or could my SD card be broken after months of heavy logging?</p>
| <p>It sounds like your SD card has likely failed. Try connecting it to a computer with an SD card reader. If it works at all, back it up immediately if you have files you wish to keep. Then try reading and writing files on it. Also if you have a spare SD card, try to use that in the Yun after setting it up appropriately. That should help narrow down the cause to either the Yun or the SD card.</p>
|
13372 | |programming|arduino-mega|pull-up| | Using an Arduino as an LED controller for an arcade stick | 2015-07-11T06:26:06.307 | <p>I'm attempting what seemed to be a rather simple problem at first glance, but due to my limited knowledge of Arduino workings I need some help. I'm trying to use button outputs from a PS360+ arcade controller. Each of the button terminals output +5V, and is meant to be connected through a button to the grounds on the PS360+.<br>
What I want to do is have an Arduino somewhere in between the button output and ground on the PS360+, to control and animate LEDs. What I've done so far is connect the VCC of the PS360+ to the Arduino's VIN and the ground of the Arduino to the PS360+'s button ground, which powers the Arduino. I then have a button output from the PS360+ going into the button, and the button's ground is connected to an Arduino pin. That Arduino pin's mode is set to INPUT. I then have another pin with an LED which is set to the value of the input pin.
For some reason, the Arduino seems to get random input from the button(Though it does seem to react somewhat to buttons presses), and the PS360+ does not recognize the button press. Setting the input pin to pullup mode has even less result, and never reads low.<br>
Anybody got any ideas? Here's my current circuit diagram. 1P is a +5V output. I think that it's an internal pull-up pin like the Arduino's, but I am not certain. <img src="https://i.stack.imgur.com/ZIZmp.png" alt="Circuit Diagram"></p>
<p>And my current code: </p>
<pre><code>int buttonlisten = 22;
int led = 53;
int val = 0;
void setup() {
pinMode(led, OUTPUT);
pinMode(buttonlisten, INPUT);
}
void loop() {
val = digitalRead(buttonlisten);
digitalWrite(led, val);
}
</code></pre>
<p>Thanks!</p>
| <p>I think the idea of putting the arduino between the button and ground is the problem here — <code>1P</code> appears to be the input for the controller button, and you can't expect to take an 'input' from the button on <em>both pins at once</em>.</p>
<p>Try connecting one lead of the button back to its ground, and the other to <code>1P</code> (as it would be originally I assume). Then solder/connect another lead from the button's non-grounded pin to an arduino pin designated as <code>INPUT_PULLUP</code>.</p>
<p>This way you have two pulled-up input pins connected to the same button pin, which are both pulled low (since Arduino & PS360+ share <code>GND</code>) when the button is pressed.</p>
|
13384 | |arduino-ide|c|variables| | Converting float to String | 2015-07-11T21:07:49.183 | <p>How can I convert a <code>float</code> value into a <code>String</code> object without implementing any library?</p>
<p>I'd like to avoid using <code>char</code> array.</p>
| <p>If you want to do it manually, rather than using the standard tools (<code>dtostrf()</code> for example) then you need to think mathematically.</p>
<p>A floating point number is made up of two distinct parts - the <em>integer</em> part and the <em>decimal</em> part.</p>
<p>For instance the number <code>123.4567</code> is made up of the integer part 123 and the decimal part 4567. Chopping off the integer portion is simple to do, and if that happens to be just one digit then you can simply add that as the first digit of your output. In this case, though, it isn't.</p>
<p>So what to do? Simple: keep dividing the number by 10 until it is just one digit. But <em>be sure to count the number of times you divide by 10</em>. So the example above would end up as 1.234567 with a divide count of 2. This is the same as the scientific representation, 1.234567×10².</p>
<p>So now you have it divided you can chop off the integer (just cast it to an int), add that integer part to your string, then remove it from the source number. So you end up with "1" and 0.234567 and a count of 2.</p>
<p>Now multiply by 10 and subtract one from your count, so you get 2.34567 and a count of 1. Grab the integer portion and add it to your string, then remove it from your number.</p>
<p>Keep repeating until your count is 0, at which point you have now done all the integer portion - so you can now add a "." to your string.</p>
<p>You now just keep repeating the same process again and again until the <em>absolute</em> value of the count equals the number of decimal places you want to print.</p>
<p>For negative numbers you should start by placing a "-" in your string, then taking the <em>absolute</em> value of the number (the number as a positive).</p>
<p>Or you just use the standard library function <code>dtostrf()</code>.</p>
|
13388 | |web-server| | Arduino webserver: faster alternative to "indexof" for parsing GET requests? | 2015-07-12T00:17:58.657 | <p>I have a webserver successfully running on an Arduino Mega, but I'm trying to make sure it's parsing the GET requests in the fastest way possible. This is what the relevant code for the GET requests looks like:</p>
<pre><code>String readString;
EthernetClient client = server.available();
if (client) {
while (client.connected()) {
if (client.available()) {
char c = client.read();
if (readString.length() < 20) {
readString += c;
}
...
...
if (readString.indexOf("?a1o") >0){
mySwitch.send(a1o, 24);
}
if (readString.indexOf("?a1c") >0){
mySwitch.send(a1c, 24);
}
</code></pre>
<p>The sketch checks for 40 possible GET variables. I'm running it as a local webserver with the address: <a href="http://192.168.0.180" rel="nofollow">http://192.168.0.180</a>.</p>
<p>-Is there a command faster than "indexOf" that I could be using?</p>
<p>-I saw some information suggesting that sometimes "parseInt" can be faster. Is there any way for me to make that work even though my local base URL is already full of integers? I would be willing to convert the commands into integers (like "11" instead of "a1o") if there was a way to use parseInt or another faster command with it.</p>
<p>Thanks!</p>
|
<p>Well, for fast parsing I wouldn't use String for a start. I've written an example (below) which does away with the String class, and also demonstrates parsing the line once.</p>
<pre class="lang-C++ prettyprint-override"><code>#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address and IP address for your controller below.
byte mac[] = { 0xB3, 0x8D, 0x72, 0x1D, 0xCE, 0x91 };
// Our IP address
IPAddress ip(10,0,0,241);
// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);
void setup()
{
// Open serial communications and wait for port to open:
Serial.begin(115200);
while (!Serial) { } // wait for serial port to connect.
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
server.begin();
Serial.print(F("Server is at "));
Serial.println(Ethernet.localIP());
} // end of setup
// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 100;
// the maximum length of paramters we accept
const int MAX_PARAM = 10;
// Example GET line: GET /?foo=bar HTTP/1.1
void processGet (const char * data)
{
// find where the parameters start
const char * paramsPos = strchr (data, '?');
if (paramsPos == NULL)
return; // no parameters
// find the trailing space
const char * spacePos = strchr (paramsPos, ' ');
if (spacePos == NULL)
return; // no space found
// work out how long the parameters are
int paramLength = spacePos - paramsPos - 1;
// see if too long
if (paramLength >= MAX_PARAM)
return; // too long for us
// copy parameters into a buffer
char param [MAX_PARAM];
memcpy (param, paramsPos + 1, paramLength); // skip the "?"
param [paramLength] = 0; // null terminator
// do things depending on argument (GET parameters)
if (strcmp (param, "foo") == 0)
Serial.println (F("Activating foo"));
else if (strcmp (param, "bar") == 0)
Serial.println (F("Activating bar"));
} // end of processGet
// here to process incoming serial data after a terminator received
void processData (const char * data)
{
Serial.println (data);
if (strlen (data) < 4)
return;
if (memcmp (data, "GET ", 4) == 0)
processGet (&data [4]);
} // end of processData
bool processIncomingByte (const byte inByte)
{
static char input_line [MAX_INPUT];
static unsigned int input_pos = 0;
switch (inByte)
{
case '\n': // end of text
input_line [input_pos] = 0; // terminating null byte
if (input_pos == 0)
return true; // got blank line
// terminator reached! process input_line here ...
processData (input_line);
// reset buffer for next time
input_pos = 0;
break;
case '\r': // discard carriage return
break;
default:
// keep adding if not full ... allow for terminating null byte
if (input_pos < (MAX_INPUT - 1))
input_line [input_pos++] = inByte;
break;
} // end of switch
return false; // don't have a blank line yet
} // end of processIncomingByte
void loop()
{
// listen for incoming clients
EthernetClient client = server.available();
if (client)
{
Serial.println(F("Client connected"));
// an http request ends with a blank line
boolean done = false;
while (client.connected() && !done)
{
while (client.available () > 0 && !done)
done = processIncomingByte (client.read ());
} // end of while client connected
// send a standard http response header
client.println(F("HTTP/1.1 200 OK"));
client.println(F("Content-Type: text/html"));
client.println(F("Connection: close")); // close after completion of the response
client.println(); // end of HTTP header
client.println(F("<!DOCTYPE HTML>"));
client.println(F("<html>"));
client.println(F("<head>"));
client.println(F("<title>Test page</title>"));
client.println(F("</head>"));
client.println(F("<body>"));
client.println(F("<h1>My web page</h1>"));
client.println(F("<p>Requested actions performed"));
client.println(F("</body>"));
client.println(F("</html>"));
// give the web browser time to receive the data
delay(10);
// close the connection:
client.stop();
Serial.println(F("Client disconnected"));
} // end of got a new client
} // end of loop
</code></pre>
<p>The incoming lines from the client are captured in a static buffer. This eliminates issues with memory fragmentation (caused by using String).</p>
<p><code>processIncomingByte</code> is called for each byte from the client. Once an entire line is assembled it calls <code>processData</code>. If that finds a "GET " line it calls <code>processGet</code>. That looks for the parameters on the GET line. The GET line looks like this:</p>
<pre class="lang-C++ prettyprint-override"><code>GET /?bar HTTP/1.1
</code></pre>
<p>So we need to get between the "?" and the next space, to get the parameter ("bar" in this case). This can be accomplished by finding their positions with <code>strchr</code>. </p>
<p>Finally (as a simple example) I tested with strcmp for a direct match on various words. You could probably make that more efficient but I doubt it would matter much.</p>
|
13389 | |arduino-ide|c|strlen| | Number of elements in an array char | 2015-07-12T00:30:49.277 | <p>What kind of function can I use to know how many elements are in an array char?</p>
<p>sizeof() gives the number of 'spaces' available so it doesn't work for me.</p>
| <p>I know you have your answer from @NickGammon, but I'd just like to add a bit more in-depth information about how all this works.</p>
<p><code>sizeof()</code> is not a function in the normal sense of the word. It is an operator which gives you the number of bytes of memory allocated to whatever you pass to it. If you pass it an array then it returns the number of bytes that array has available to it. If you pass it a pointer to an array then it returns the size of that pointer, not the size of the array. If you pass it an integer variable it returns the number of bytes used by that integer variable (2 on an 8-bit system like AVR, 4 on a 32-bit system like the Due).</p>
<p>So some examples:</p>
<pre><code>char array[50] = "hello";
// sizeof(array) = 50.
char *array_p = array;
// sizeof(array_p) = 2 or 4 depending on architecture.
char single = 'a';
// sizeof(single) = 1.
char string[] = "hello";
// sizeof(string) = 6 (5 letters plus \0) - it allocates the memory at compile time to fit the string
</code></pre>
<p>Now <code>strlen()</code>. How exactly does that differ from <code>sizeof()</code>? Simply put, <code>strlen()</code> counts the number of characters in a character array up until it reaches the character <code>\0</code> which is the "NULL" terminating character of a C string. Let's take the examples before but use strlen instead:</p>
<pre><code>char array[50] = "hello";
// strlen(array) = 5.
char *array_p = array;
// strlen(array_p) = 5.
char single = 'a';
// strlen(single) = ERROR! strlen() doesn't operate on single characters.
char string[] = "hello";
// strlen(string) = 5.
</code></pre>
<p>You notice it always returns the number of characters in the string up to, but not including, the trailing <code>\0</code> character.</p>
<p>In its simplest form the <code>strlen()</code> function might look like this:</p>
<pre><code>int strlen(const char *data) {
int c = 0;
const char *p = data;
while (*p) {
c++;
p++;
}
return c;
}
</code></pre>
<p>Basically it starts at the first character in the string (<code>*p = data</code>), examines if it's a <code>\0</code> or not (<code>while (*p)</code>), increments the count of characters (<code>c++</code>) and moves on to the next character in the string (<code>p++</code>).</p>
<p>If you want to iterate through your string in your program you could call <code>strlen()</code> first to get the number of characters in the string then use that value in a loop. That is a bit wasteful, since <code>strlen()</code> first iterates through the string, so you end up iterating through it twice. It is far more efficient to learn how best to step through each character in the string until you find the terminating character, such as how the <code>strlen()</code> function uses the <em>pointer</em> to move through memory. You can also see just how vital it is that you ensure the <code>\0</code> character exists at the end of the string, otherwise how will functions like <code>strlen()</code> know when to stop? They can't know how long the string is (<code>sizeof()</code> will return the size of the pointer it is passed, not the size of the array), so they have to have some kind of manual marker, and the convention in C is to use <code>\0</code>.</p>
<p>Note that Arduino's <code>print()</code> functions actually do it very inefficiently. If you do something like:</p>
<pre><code>char message[] = "Hello";
Serial.println(message);
</code></pre>
<p>It will actually do quite a lot of work it doesn't <em>really</em> need to. Taken step by step it:</p>
<ol>
<li>calls println(message)</li>
<li>which calls write(message)</li>
<li>which gets the string length with strlen(message)</li>
<li>and calls write(message, length)</li>
<li>which then loops from 0 to length-1 sending each character of message to write() in turn.</li>
<li>finally prints the <code>\r\n</code> for the new-line.</li>
</ol>
<p>So it actually ends nested around 4 functions deep, and iterates the entire string twice. A classic example of how to waste processing time. By iterating through the string once looking for the <code>\0</code> character in the <code>write(message)</code> function (step 2) it would operate at least twice as fast. Good old Arduino...</p>
|
13393 | |arduino-ide| | How to program for two Arduinos with different code but share one same .h? | 2015-07-11T12:30:30.363 | <p>I am now programming for two Arduinos. One is used as Tx and the other is Rx. Of course they are programmed by different codes, but they share some same .h files I programmed(let's say 'share.h'), which are not libraries and shouldn't be put in Arduino's 'library' folder. </p>
<p>So I put 'share.h' and main.ino in one folder, and the ino is like:</p>
<pre><code>#include "share.h"
#define TX
#ifdef TX
void setup(){...something for Tx...}
void loop(){...}
#else
void setup(){...something for Rx...}
void loop(){...}
#endif
</code></pre>
<p>The shortage is that every time I want to update my code to the two unos, I have to: first change the board port to 40(the Tx uno) in ide, add the <code>#define</code> line, and upload. Then I have to change port to 42(the Rx one), comment the <code>#define</code> line and upload. So inconvenient! </p>
<p>So do you have any good ideas? Much appreciation!</p>
| <p>You could also use:</p>
<pre><code>
in transmitter.ino
#define TX 1
#include "share.h"
in receiver.ino
#define RX 1
#include "share.h"
</code></pre>
|
13402 | |arduino-uno|bootloader| | How to test Arduino board? | 2015-07-12T21:39:42.697 | <p>A little history: I have two Arduino Uno and I couldn't program them by IDE, I got these errors:</p>
<pre><code>avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
</code></pre>
<p>So I googled it for a while and I suspect of missing bootloader on atmega micro on the board, as I don't have AVR programmer I programmed both Arduinos with Raspberry Pi and Arduino IDE tool through ICSP pins.</p>
<p>It (burning bootloader) runs perfectly on both Arduino. One of them got fixed and got back to normal, but the other one gave me same error, so I changed their Atmega micro, but same result. Second Arduino (bad one) can't transfer program to AVR even with other one (good one) AVR so both AVRs on the boards are good.
The program (blink LED) run even on the bad Arduino and pin 13 blink.</p>
<p>My questions are:</p>
<p>How could I test the suspected Arduino board? Is the second Atmel micro near usb female port need bootloader too?</p>
<blockquote>
<p><strong>Update 1</strong>: I follow <a href="http://bartruffle.blogspot.com/2013/09/dfu-programming-atmega16u2-on-arduino.html" rel="nofollow">this tutorial</a> but my Arduino couldn't go to DFU
mod by shorting the pins. When I connect those pins led pin 13 not blink and lsusb command show Arduino not Atmel.</p>
<p><strong>Update 2</strong> : I went through <a href="https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno">this question</a> and <a href="http://www.gammon.com.au/bootloader" rel="nofollow">this
troubleshoot</a> to upload bootloader to Atmel USB device but my
second Arduino (bad one) didn't respond and gave me this error :</p>
</blockquote>
<pre><code>Atmega chip detector.
Written by Nick Gammon.
Version 1.17
Compiled on Jul 13 2015 at 11:14:35 with Arduino IDE 105.
Attempting to enter ICSP programming mode......................................................
Failed to enter programming mode. Double-check wiring!
Programming mode off.
</code></pre>
<blockquote>
<p>Is it possible my Atmega16U2 chip is burned?</p>
<p><strong>Update 3</strong> : I do reach the point that I am pretty sure Atmega16U2 is
dead and it isn't responding to its ICSP pins and it blocks any USB to AVR connection. I check the wiring and I
test it on good Arduino and its sequence are correct and it works on good one. Now what can I
do, as Atmega16U2 is not rechangeable, should I throw bad Arduino away?</p>
</blockquote>
| <p>This answer is for your 3dr Update - should you throw it away?
I'd say no, if you are comfortable with using the Raspberry PI as programmer, as you already did.
You will not be able to use the USB-based programming, nor you will be able to emulate USB peripherals, but that's it.</p>
<p>Everything else will (or should) work normally, so why would you throw it away? :-)</p>
<p>I also suggest you grab the stronger magnifying lens you can find and have a look at the soldering of all the components. Especially those connected to the Atmega16U and the chip itself. Maybe it's not broken, but there is some short caused by conductive debris or by some excess of soldering material. If that's the case, it might be easy to remove it.</p>
|
13407 | |programming|led|uploading|sketch| | Separate ATmega 2560 - turn on a single LED - troubleshooting | 2015-07-13T08:09:51.377 | <p>I have got my own PCB with "some stuff" on it and first I want to make it run a simple "turn on LED".</p>
<p>My setup:</p>
<ul>
<li>Atmega 2560</li>
<li>LED connected to PE4 (D2 in Arduino language) => PE4 - LED - 1K resistor - 5V</li>
<li>ceramic resonator (CSTCE16M0V53-R0 16MHZ) connected to XTAL1 + XTAL2 with 1MOhm resistor in between</li>
<li>all VINs are pulled to GND with capacitors</li>
</ul>
<p><img src="https://i.stack.imgur.com/c8hIN.png" alt="resonator VINs GNDs" />
<img src="https://i.stack.imgur.com/ZeKns.png" alt="RESET circuit" />
<img src="https://i.stack.imgur.com/UP9Az.png" alt="status LEDs" /></p>
<p>Upload is working through ICSP (MISO, MOSI, SCK, RESET, 5V, GND) with an USBasp</p>
<p>Here is my <strong>Arduino sketch</strong>, which I upload through the Arduino software:</p>
<pre><code>void setup() {
pinMode(2, OUTPUT);
}
void loop() {
digitalWrite(2, LOW);
}
</code></pre>
<p>I checked the fuses on the Atmega as well:</p>
<pre><code>avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as D8
avrdude: safemode: efuse reads as FD
avrdude: safemode: Fuses OK (H:FD, E:D8, L:FF)
</code></pre>
<p>avrdude uploads successfully: <em>(output truncated!)</em></p>
<pre><code>avrdude: auto set sck period (because given equals null)
avrdude: AVR device initialized and ready to accept instructions
Reading | ################################################## | 100% 0.01s
avrdude: Device signature = 0x1e9801
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: auto set sck period (because given equals null)
avrdude: writing flash (1518 bytes):
Writing | ################################################## | 100% 5.47s
avrdude: 1518 bytes of flash written
avrdude: reading on-chip flash data:
Reading | ################################################## | 100% 3.45s
avrdude: verifying ...
avrdude: 1518 bytes of flash verified
avrdude done. Thank you.
</code></pre>
<p>Problem: the LED doesn't work. It is OFF all the time.</p>
<p>Any ideas why it is not working?</p>
| <p>You are saying that the LED lights if you write LOW to it.</p>
<blockquote>
<p>I need to pull the output pin to LOW to make the LED work </p>
</blockquote>
<p>That's exactly what you expect.</p>
<p><img src="https://i.stack.imgur.com/cKpuI.png" alt="LED wiring"></p>
<p>Since the other end of the LED is wired to +5 V, then you need to drive the pin low to have a voltage difference over the LED, and for it to light.</p>
<hr>
<blockquote>
<p>I double checked the Atmega and it is a ATmega2560V, which is rated for 8Mhz. Any chance to fix this with the existing PCB? Change the Fuses to use the internal clock? </p>
</blockquote>
<p>Yes, I suggest you do that.</p>
<p>Look at <a href="http://www.engbedded.com/fusecalc" rel="nofollow noreferrer">Engbedded Atmel AVR® Fuse Calculator</a> to see what to set them to. I suggest the internal 8 MHz oscillator.</p>
|
13415 | |arduino-mega|pwm|servo| | Arduino Mega PWM pins stop working for LEDs once servo is attached? | 2015-07-13T14:56:41.600 | <p>I can get LEDs to fade properly using PWM on pins 44-46 on the Mega2560 when I don't have a servo attached, but once I "attach" the servo in the code, then PWM pins 44-46 don't work for PWM. They can still work with digitalWrite, but not with analogWrite.</p>
<p>This is the code:</p>
<pre><code>#include <Servo.h>
Servo myservo;
int led = 46;
void setup() {
myservo.attach(3);
pinMode(led, OUTPUT);
analogWrite(led, 60);
}
void loop() {}
</code></pre>
<p>If I comment out the "myservo.attach(3);" line, then PWM works for the LED pin. Otherwise the LED stays off. Why would PWM on pins 44-46 stop working once the servo is attached?</p>
| <p>Looks like the mega has some clever <a href="https://arduino-info.wikispaces.com/Timers-Arduino" rel="nofollow">servo handling features</a>. Servo control always uses a timer of some sort and can conflict with the pwm timer. The first 12 servos knock out pins 44,45,46 ...</p>
<blockquote>
<p>For Arduino Mega it is a bit more difficult. The timer needed depends on the number of servos. Each timer can handle 12 servos. For the first 12 servos timer 5 will be used (losing PWM on Pin 44,45,46). For 24 Servos timer 5 and 1 will be used (losing PWM on Pin 11,12,44,45,46).. For 36 servos timer 5, 1 and 3 will be used (losing PWM on Pin 2,3,5,11,12,44,45,46).. For 48 servos all 16bit timers 5,1,3 and 4 will be used (losing all PWM pins).</p>
</blockquote>
|
13416 | |arduino-uno|reset| | How does one design for the power on transient conditions? | 2015-07-13T15:10:19.383 | <p>Following on from the question <a href="https://arduino.stackexchange.com/questions/1477/reset-an-arduino-uno-by-an-command-software">Reset an Arduino UNO by an command (software)</a> and the excellent <a href="https://arduino.stackexchange.com/questions/1477/reset-an-arduino-uno-by-an-command-software#answer-1478">answer</a> provided by <a href="https://arduino.stackexchange.com/users/60/mpflaga">mpflaga</a>, the comment addressing option (1) suggests that there are design considerations for connecting an output pin to the RESET pin. </p>
<blockquote>
<p>Option 1. or a variant can be a clean enough way to do this as long as
power on transient conditions are designed for.
- <a href="https://arduino.stackexchange.com/users/6959/russell-mcmahon">Russell McMahon</a></p>
</blockquote>
<p>or more ominuously</p>
<blockquote>
<p>From everything I've read, the first option is not recommended. - <a href="https://arduino.stackexchange.com/users/11/sachleen">sachleen</a></p>
</blockquote>
<p>Could someone tell me exactly what those considerations are? Is it that it is not as simple as connecting the two with a jumper cable - is additional circuitry (i.e. an RC timer) required, or is there a software solution?</p>
<p>I find the latter option unlikely as the device is rebooting, so unless the software fix is to ignore hardware interrupts (since a RESET is simply that, and the state of the output pins is unlikely to be known, or stable at reboot) for a few mS after reboot, I presume that a hardware fix is required.</p>
|
<p>Atmel specifically recommend against driving /RESET low from an output pin, because the first thing that the reset process does is set all pins to high impedance, thus cancelling the reset pulse before the recommended reset pulse length has elapsed.</p>
<p>The recommended use of the watchdog timer does not suffer from these limitations. It is <em>designed</em> to reset the board (or there would be no purpose to having it) and it does a proper reset (unlike jumping to address 0x0000).</p>
<hr>
<h3>Reference</h3>
<p><a href="http://atmel.force.com/support/articles/en_US/FAQ/Software-Reset" rel="noreferrer">Atmel knowledge base - Software Reset</a></p>
<blockquote>
<p>If you want to perform a software reset of your AVR you should use the internal Watchdog. Simply enable it and let it time out. When the Watchdog triggers it resets the program counter back to 0, clears all the registers and performs all the other tasks. This operation gives the same result as pulling the RESET line low.</p>
<p>You should not try to:</p>
<ul>
<li><p>Use another pin of the AVR to pull the external RESET line. The pins of the AVR are tristated halfway through the minimum reset time, this releases the RESET line and hence nothing happens.</p></li>
<li><p>Jump to program location 0. Jumping to program location 0 does not clear all the registers and hence you do not have a "clean" reset.</p></li>
</ul>
</blockquote>
<hr>
<p>Their suggested code to reset the processor:</p>
<pre class="lang-C++ prettyprint-override"><code>#include <avr/io.h>
#include <avr/wdt.h>
#define Reset_AVR() wdt_enable(WDTO_30MS); while(1) {}
int main(void)
{
Reset_AVR();
}
</code></pre>
|
13421 | |arduino-mega| | Arduino code cannot continute process | 2015-07-13T17:20:27.680 | <p>Two days ago, my code is working fine on the arduino board. But yesterday, and today I tried so many time to upload the arduino code, which contains 1000 lines of code. It was successfully uploaded the code into arduino. But it only upload half code into arduino when I saw the serial monitor results (I use serial println(); test where the code is located. ) I am so confusing, why the code is working fine two days ago. but later, only half code being used. Please help.</p>
<p>Here is the memory I left when I uploaded it. </p>
<p>Sketch uses 48,314 bytes (19%) of program storage space. Maximum is 253,952 bytes.
Global variables use 2,603 bytes (31%) of dynamic memory, leaving 5,589 bytes for local variables. Maximum is 8,192 bytes.</p>
<pre><code>Here is the code it stuck :
Get Parameters
//
// This function reads the information from the SD card for a given monitoring
// site.
//
</code></pre>
<p>//</p>
<pre><code>int getParameters(){
String lowerLimit, upperLimit;
char buffer[36];
char newChar;
int index, index1, index2, index3, line, theLength, numSensors;
myFile.setTimeout(2000);
line = 0;
while (myFile.available()) {
index = 0;
do{
newChar = myFile.read();
buffer[index] = newChar;
index += 1;
}
while(newChar != 10);
buffer[index] = 0;
theLines[line] = buffer;
Serial.print(theLines[line]);
//here the result is something like this
//theLines[0] , class 111
//theLines[1] , 192.168.1.10
//theLines[2] , Mac Address
line += 1;
}
//so it is working fine above the code. But here is the problem stuck.
//the code cannot go through the rest of the code below. Nothing happened!!!
for (int line = 0; line < 10; line++){
Serial.print(theLines[line]);
}
</code></pre>
| <p>A portion of your code is shown below.</p>
<pre><code> myFile.setTimeout(2000);
....
while (myFile.available()) {
index = 0;
do {
newChar = myFile.read();
buffer[index] = newChar;
index += 1;
} while(newChar != 10);
....
}
</code></pre>
<p>Apparently your code is accepting and printing several lines of option setting text and then hangs up in the code extract shown above.</p>
<p>Suppose, for example, one extra character appears after the supposedly-last linefeed character. Your <code>while (myFile.available())</code> loop will run again. It will store the extra character, then try to read another character. If another character isn't available, <code>newChar = myFile.read();</code> will return a -1 that your code will store. That will happen repeatedly, clobbering RAM.</p>
<p>To see if this is what's happening, you could change <code>while(newChar != 10);</code> to (eg) <code>while(newChar != 10 && index<36);</code>. If the code then stops hanging up, look into where the extra character is coming from.</p>
|
13426 | |arduino-uno|programming|c++|string| | Implementing DES or AES Encryption with DateTime Synchronization on Uno | 2015-07-13T22:24:53.407 | <p>We are trying to implement AES or DES encryption using an Arduino Uno.</p>
<p>We have a keypad module attached that will be used to input integers. A String should be generated based on the entered data and encrypted using AES or DES.</p>
<p>We have tried several online libraries with no success due to the constraints put on the "plain text" size. </p>
<p>An example pseudo-code for the above:</p>
<pre><code>string key = "This is a key";
string plain = "This is the keypad input" + keypadInput + "and some other random stuff"; <- This should have any size.
var cipher = AES.encode(plain, key);
print(cipher);
var decoded = AES.decode(cipher, key);
print(decoded);
</code></pre>
<p>Could someone please point to the right direction on how to do this?</p>
|
<blockquote>
<p>We have no experience with the byte[] objects and whatnot.</p>
</blockquote>
<p>Might be time to do a few tutorials. You won't get far programming if you don't learn how to use arrays.</p>
<p>The <strong>string</strong> class is part of the STL (Standard Template Library) which does not come pre-installed on the Arduino (however you can download it if you want to).</p>
<p><a href="http://andybrown.me.uk/ws/2011/01/15/the-standard-template-library-stl-for-avr-with-c-streams/" rel="nofollow">The Standard Template Library (STL) for AVR with C++ streams </a></p>
<hr>
<p>Briefly, however you could do something like this:</p>
<pre class="lang-C++ prettyprint-override"><code>char key [20] = "This is a key";
char keypadInput [16]; // whatever they entered
char plain[80];
strcpy (plain, "This is the keypad input");
strcat (plain, keypadInput);
strcat (plain, "and some other random stuff");
</code></pre>
<p>The example code doesn't have any size checking. You would want to make sure that you don't put more than 79 characters into "plain" (to allow for the terminating 0x00 character). For example, look up <strong>strncat</strong>.</p>
<hr>
<blockquote>
<p>Can you please elaborate on how DES or AES as described in the question can be implemented?</p>
</blockquote>
<p>Have you done much research? Have you Googled <code>Arduino AES encryption</code> like I just did? I got this as the first hit:</p>
<p><a href="http://forum.arduino.cc/index.php?topic=88890.0" rel="nofollow">Topic: new AES library - Arduino Forum</a></p>
<blockquote>
<p>I've written an AES (Advanced Encryption Standard) library for Arduino. It supports 128, 192 and 256 bit key sizes. Code space overhead is about 4KB I think, each instance requires 240 bytes RAM for subkeys. Fairly tightly coded and checked against official test vectors for ECB mode. Also CBC mode supported.</p>
</blockquote>
<hr>
<blockquote>
<p>It seems that if value of plain is larger than 16 characters the library will encrypt the first 16 characters only... Is this an Arduino Uno limitation?</p>
</blockquote>
<p>I don't want to seem unhelpful, but you really should do some research before asking these questions. From <a href="https://en.wikipedia.org/wiki/Advanced_Encryption_Standard" rel="nofollow">Wikipedia - Advanced Encryption Standard (AES)</a>:</p>
<blockquote>
<p>AES is a variant of Rijndael which has a fixed block size of 128 bits, and a key size of 128, 192, or 256 bits. </p>
</blockquote>
<p>A "fixed block size of 128 bits" means you encrypt 128 bits at a time, that is, <code>128/8 = 16 bytes</code>.</p>
<p>So no, it is not an Arduino Uno limitation, it is the way AES works. </p>
<hr>
<p>Also see <a href="https://en.wikipedia.org/wiki/Data_Encryption_Standard" rel="nofollow">Wikipedia - DES</a>.</p>
<blockquote>
<p>In the case of DES, the block size is 64 bits.</p>
</blockquote>
<p>So DES does 8 bytes at a time.</p>
<hr>
<p>What you can do with a password is to <strong>hash</strong> it, for example: <a href="https://en.wikipedia.org/wiki/Secure_Hash_Algorithm" rel="nofollow">Secure Hash Algorithm</a> or <a href="https://en.wikipedia.org/wiki/MD5" rel="nofollow">MD5</a> (amongst others). These algorithms take a variable length string and return a fixed "hash". In the case of MD5 the output is a 128-bit field.</p>
<p>You could then encrypt that 128-bit hash, if you want to keep it a secret.</p>
<hr>
<blockquote>
<p>Would encrypting the 16 bytes and then append the next 16 bytes and so on result to the same output as if the whole plain text was encrypted in the first place in one go? </p>
</blockquote>
<p>The suggestion by @BrettAM was, if you want to encrypt more than 16 bytes, do them 16 bytes at a time, padding if necessary the final block.</p>
<p>eg.</p>
<pre class="lang-C++ prettyprint-override"><code>AAAAAAAAAAAAAAAA BBBBBBBBBBBBBBBB CCCCCCCCCC000000
encrypt encrypt encrypt
LLLLLLLLLLLLLLLL MMMMMMMMMMMMMMMM NNNNNNNNNNNNNNNN
decrypt decrypt decrypt
AAAAAAAAAAAAAAAA BBBBBBBBBBBBBBBB CCCCCCCCCC000000
</code></pre>
<p>In this example the final block was padded with zeros. Now the receiving end decrypts in 16-byte blocks.</p>
|
13429 | |programming|arduino-ide|c| | deprecated conversion from string constant to 'char*' | 2015-07-14T02:20:15.777 | <p>What does this error means?
I can't solve it in any way.</p>
<blockquote>
<p>warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]</p>
</blockquote>
| <p>I have this compilation error: </p>
<pre><code>TimeSerial.ino:68:29: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
if(Serial.find(TIME_HEADER)) {
^
</code></pre>
<p>Please replace this line:<br>
<code>#define TIME_HEADER "T" // Header tag for serial time sync message</code></p>
<p>with this line:<br>
<code>#define TIME_HEADER 'T' // Header tag for serial time sync message</code></p>
<p>and compilation goes well.</p>
|
13431 | |programming|arduino-ide|c|sketch| | Empty char variable | 2015-07-14T02:46:40.813 | <p>How do I empty all the values inside a variable <code>char array[256];</code>?</p>
<p>I tried a for loop assigning an empty value at each iteration, but it doesn't compile.</p>
| <p>There is a single-line command you can use:</p>
<pre><code>memset(array, 0, 256);
</code></pre>
|
13452 | |arduino-ide|library|gps|tinygps| | TinyGPS (Plus) Library | 2015-07-14T21:07:54.903 | <p>Is there a particular function in the library TinyGPS or TinyGPS Plus which outputs the raw NMEA sentences? I couldn't find anything about it on the website guide of the library.</p>
|
<p>There doesn't seem to be, but what you could do is print each character as it arrives. From their example code:</p>
<pre class="lang-C++ prettyprint-override"><code> while (nss.available())
{
if (gps.encode(nss.read())) // <--- pass to TinyGPS
return true;
}
</code></pre>
<p>So, change that to be:</p>
<pre class="lang-C++ prettyprint-override"><code> while (nss.available())
{
char c = nss.read(); // <--- get the incoming character
Serial.print (c); // <--- print it
if (gps.encode(c)) // <--- now pass it to TinyGPS
return true;
}
</code></pre>
|
13459 | |spi|can-bus| | Connect the Sparkfun CAN bus shield with an RFduino | 2015-06-30T12:33:06.500 | <p>I have a problem which I am working on for some days now. I do have knowledge in electronics, but not extensively. I also posted this question in the <a href="http://forum.rfduino.com/index.php?topic=1146.0" rel="nofollow noreferrer">RFduino Forum</a> but couldn't get any good answers.</p>
<p>What I am trying to do: I want to connect the Sparkfun CAN bus shield to the RFduino. I am using the code further below. It compiles without problem and <strong>does work</strong> with my Arduino Leonardo!</p>
<p>I used a logic analyser (ignore the filled shapes, some display error) to further narrow down the problem and found the following on the <strong>RFduino</strong>:
<img src="https://i.stack.imgur.com/yNB30.png" alt="Picture of the logic analyser on the RFduino"></p>
<p>On the <strong>Leonardo</strong>, it looks different:
<img src="https://i.stack.imgur.com/JhnnI.png" alt="Picture of the logic analyser on the Leonardo"></p>
<p>It seems like I don't get a response on the MISO line! I played around with different speeds, but nothing seemed to work. </p>
<p>I do have a suspicion however: The RFduino works with 3.3V, while the Leonardo works with 5V. So the logic signals on the RFduino can only achieve 3.3V P-P. I confirmed this with my old CRO, LOW is at GND and HIGH at 3.3V. The Leonardo has 5V P-P.
On page 70 of the datasheet for the MCP2515 (the chip used on the shield), it says that the supply voltage VDD ranges from 2.7V to 5.5V. So supply voltage should be ok. V_INPUT_HIGH ranges from 2.31 to 4.3V. V_INPUT_LOW ranges from -0.3V to 0.495V. I am in this range! Similarly so for the V_OUTPUT_LOW (up to 0.6V) and V_OUTPUT_HIGH (at least 2.8V). Could this nevertheless be a problem?</p>
<p>What would you try or change?</p>
<p><a href="http://ww1.microchip.com/downloads/en/DeviceDoc/21801d.pdf" rel="nofollow noreferrer">MCP2515 Datasheet</a></p>
<pre><code>#include <SPI.h>
// demo: CAN-BUS Shield, send data
#include <mcp_can.h>
MCP_CAN CAN0(SS); // Set CS to pin 10
unsigned char stmp[8] = {0, 1, 0, 3, 0, 5, 0, 7};
void setup()
{
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// init can bus, baudrate: 500k
if(CAN0.begin(CAN_500KBPS) == CAN_OK) Serial.print("can init ok!!\r\n");
else Serial.print("Can init fail!!\r\n");
// send data per 100ms
}
void loop()
{
// // send data: id = 0x00, standrad flame, data len = 8, stmp: data buf
// CAN0.sendMsgBuf(0x00, 0, 8, stmp);
}
</code></pre>
| <p>Ok, I found the solution. The fix first: I had to <strong>physically connect the reset line from the RFduino to the MCP2515 reset pin.</strong>
On page 55 in the datasheet of the MCP2515 it says that you can either reset it by pulling the reset line low or by sending a command over the SPI. The library I used is sending this reset command, but it isn't working for some reason. The logic analyser shows me this signal, it is the first recorded. Maybe it is a timing issue, that the reset has to be sent at the same time as the RFduino resets. Connecting the reset pin solves this issue, because then the RFduino and the MCP2515 are being reset at the same time.
If anybody knows more about this, feel free to tell me!</p>
|
13465 | |serial|arduino-mega|xbee| | Arduino Xbee AT command mode | 2015-07-15T05:37:07.360 | <p>I have 2 Xbee Series 2 modules.
One of it is connected to arduino via an adapter. And Ground 5V, as well as Rx>>Tx and Tx>>Rx. </p>
<p>The xbee is configured AT mode Coordinator.</p>
<p>I want to use the serial monitor in arduino to change the parameters of the xbee, such as DH or DL or PAN ID things like this.</p>
<p>Is there a way for the xbee to display its "OK" response after entering command mode on the serial monitor?</p>
| <p>Because you have an Arduino Mega, you can set it up to use it like a USB-to-UART adapter by using the following code (<a href="https://www.arduino.cc/en/Tutorial/MultiSerialMega" rel="nofollow">source</a>):</p>
<pre><code>void setup() {
// initialize both serial ports:
Serial.begin(9600);
Serial1.begin(9600);
}
void loop() {
// read from port 1, send to port 0:
if (Serial1.available()) {
int inByte = Serial1.read();
Serial.write(inByte);
}
// read from port 0, send to port 1:
if (Serial.available()) {
int inByte = Serial.read();
Serial1.write(inByte);
}
}
</code></pre>
<p>Basically what this does is it takes the data it receives from the USB port via <code>Serial</code> and transmits it to <code>Serial1</code> and then also reads from the UART port via <code>Serial1</code> and transmits it back to the computer via <code>Serial</code>. With this code running you should be able to hook up the XBee to RX1 and TX1 and communicate to it using the Serial Monitor.</p>
|
13469 | |analogread|sd-card|signal-processing| | Signal sampling: losing data every 103 points when it is recorded in SD | 2015-07-15T11:08:46.373 | <p>I'm working on a system of acquisition and ECG datalogging with the Arduino, and I'm having the following problem:
I'm losing data every 103 points (just 103). No matter the sampling frequency to use, every 103 points, some points are lost, damaging the signal sampling.
It could be the recording time on the SD card, but even when the SD.close () command is run only once, the data is lost.
Here is a simple test algorithm with a 100 Hz sine wave at the entrance.</p>
<hr>
<pre><code>#include <SD.h>
#include <SPI.h>
int CS = 4;
int ECG_PIN = 1;
int voltage;
int index = 0;
const int bufferSize = 5;
int vetor[bufferSize];
int RECORD_TIME = 20000;
File logFile;
void setup(){
pinMode(CS, OUTPUT);
pinMode(ECG_PIN,INPUT);
if(!SD.begin(CS)){
return;
}
logFile = SD.open("ECG_log.txt", O_CREAT | O_WRITE);
}
void loop(){
while(millis() <= RECORD_TIME){
voltage = analogRead(ECG_PIN);
if(logFile){
logFile.println(voltage);
delay(0.5);
}
}
logFile.close();
}
</code></pre>
<hr>
<p><img src="https://i.stack.imgur.com/tlVlK.png" alt="enter image description here"></p>
<p>What could it be? Speed analogRead ()? Problem on the SD card?</p>
<p>Sorry if the question is very basic, I am beginner, in a way, the Arduino platform. Any help will be very welcome.</p>
<p>Thanks!...</p>
| <p>It's all to do with writing to the SD card.</p>
<p>You have a buffer of 512 bytes which is one "block" of the SD card. When you have written to the card enough to fill that buffer up it has to write that buffer to the SD card and empty the buffer so you can start filling it again.</p>
<p>That writing to the SD card takes time - lots and lots of time (relatively), and it can't be doing anything else at the same time as writing to the SD card.</p>
<p>The only way you can get around that is to have your sampling performed within an interrupt - maybe a timer interrupt - so that it can interrupt the writing to the SD card. However, that's not a simple task.</p>
<p>You would need to implement a system known as <em>ping-pong</em> buffers. You have a pair of buffers for storing incoming samples within your interrupt routine. When one buffer is filled up you switch to the other buffer and signal to your main loop() routine that you have filled the buffer. It's then the job of loop() to save that buffer to the SD card and empty it ready for when the second buffer has been filled up. The name <em>ping-pong</em> comes from the game of table tennis (also known as <em>ping-pong</em>) as you are switching from one buffer to the other and back again in a constant backwards-and-forwards motion like the ball in a game of table tennis.</p>
<p>Getting the right size of buffers is also critical. You have to ensure that the time taken to fill one buffer is always going to be longer than the longest amount of time it takes to write a buffer to the SD card, including any flushing of the internal SD card buffer. The best size is probably going to be to match that internal SD card buffer so every <em>ping</em> or <em>pong</em> you will be doing an entire SD card block's worth of data - so 512 bytes.</p>
<p>That means you have 3 buffers of 512 bytes - your two ping-pong buffers and the SD card's buffer, which is 1536 bytes - not far off the limit of an Uno, so you may struggle with that. For this kind of thing it is better to use one of the boards with a more meaty chip, like the Mega2560.</p>
<p>Also the line:</p>
<pre><code>delay(0.5);
</code></pre>
<p>is meaningless. <code>delay()</code> takes an integer value, so <code>0.anything</code> is actually truncated to <code>0</code>. To delay for less than a millisecond you should use <code>delayMicroseconds()</code>.</p>
|
13470 | |arduino-uno|esp8266| | Arduino with ESP8266 | 2015-07-15T11:17:11.887 | <p>I have completed the circuit and code to interface ESP8266 module with Arduino UNO.</p>
<p>When i send <code>AT</code>,<code>AT+RST</code> from serial monitor the reply is correct .</p>
<p>But when i send AT commands to search WIFI networks (<code>AT+CWLAP</code>) & connect to WIFI (<code>AT+CWJAP="SSID","password"</code>) the reply is <code>ERROR</code>.</p>
<p>But the IP address (may be default) is obtained as <code>192.168.4.1</code>
when i send <code>AT+CIFSR</code> . </p>
<p>Here is my code</p>
<pre><code>#include <SoftwareSerial.h>
SoftwareSerial esp8266(2,3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
// This means that you need to connect the TX line from the esp to the Arduino's pin 2
// and the RX line from the esp to the Arduino's pin 3
void setup()
{
Serial.begin(9600);
esp8266.begin(9600); // your esp's baud rate might be different
}
void loop()
{
if(esp8266.available()) // check if the esp is sending a message
{
while(esp8266.available())
{
// The esp has data so display its output to the serial window
char c = esp8266.read(); // read the next character.
Serial.write(c);
}
}
if(Serial.available())
{
// the following delay is required because otherwise the arduino will read the first letter of the command but not the rest
// In other words without the delay if you use AT+RST, for example, the Arduino will read the letter A send it, then read the rest and send it
// but we want to send everything at the same time.
delay(1000);
String command="";
while(Serial.available()) // read the command character by character
{
// read one character
command+=(char)Serial.read();
}
esp8266.println(command); // send the read character to the esp8266
}
}
</code></pre>
| <p>Finally i found the solution . </p>
<p>Send <code>AT+CWMODE=1</code> first , then all other commands working fine. </p>
|
13474 | |pins|sd-card|display|shift-register|rtc| | One free pin. Need to display output for the user? | 2015-07-15T18:02:36.340 | <p>I'm working with <a href="https://punchthrough.com/bean/arduino-users-guide/" rel="nofollow noreferrer">lightblue bean</a>. I have a device that writes data to an SD card on a long button press and switches what will be written (from a list of 5 items) on short button press. </p>
<p>The output, printed both to the SD card and to serial looks like this:</p>
<pre><code>12:38, 7/15/15, subway
12:55, 7/15/15, subway
12:38, 7/15/15, bus
12:55, 7/15/15, rail
</code></pre>
<p>etc. It's basically a time stamp then a vale from this list:</p>
<pre><code>char* modes[]= {"walking", "subway", "bus", "railroad", "other"};
</code></pre>
<p>This works perfectly. But the bean has very few pins:</p>
<p><img src="https://i.stack.imgur.com/aU3Q2.png" alt="enter image description here"></p>
<ul>
<li>5 SCK -- connected to SD card. </li>
<li>4 MISO -- connected to SD card. </li>
<li>3 MOSI -- connected to SD card. </li>
<li>2 SS -- connected to SD card. </li>
<li>1 -- input button, takes long and short presses </li>
<li>0 -- </li>
<li>A1 SDA --- connected to real time clock for timestamp </li>
<li>A0 SCL --- connected to RTC (real time clock) for timestamp</li>
</ul>
<p>I have <strong><em>one</em></strong> free DIGITAL pin. I need to let the user know what they have selected. This could be done with 5 LEDs that light up next to the user's choice, or maybe displayed text? This is a portable item so a servo that points to the user's choice might be too unreliable.</p>
<p>I've done some research into shift registers. They all seem to need 3 digital pins min. If I could do it with 2 I could rework the button...</p>
<p>Ideas?</p>
| <p>The 7-segment display board is all very well, but that displays 4 digits. That isn't exactly 5 LEDs. In any case that board has a chip on it, if you are going to buy another chip you may as well get an Attiny and use that. Just have serial input (same as the 7-segment board did).</p>
<p>On the Attiny you have 8 pins, 3 of which will be reserved: Vcc, Gnd, Reset. That leaves you with 5 for the communications <em>and</em> the 5 LEDs. So, use one pin for incoming serial, or two pins for SDA/SCL, and use the remaining 3 pins for the LEDs. You can can use <a href="https://en.wikipedia.org/wiki/Charlieplexing" rel="nofollow noreferrer">Charliplexing</a> to use 3 pins to light up to 6 LEDs.</p>
<h2><img src="https://i.stack.imgur.com/ZJfsk.png" alt="Charliplexing schematic"></h2>
<p>For the fun of it, I made up an example using my Uno (it still only uses 3 pins to light 6 LEDs).</p>
<p><img src="https://i.stack.imgur.com/SYzzc.jpg" alt="Charliplexing demo"></p>
<p>There are 3 x 100 Ω resistors as in the schematic. One is completely hidden by the LEDs (leading from the middle yellow wire to the middle pins of the LEDs).</p>
<p>Code:</p>
<pre><code>const byte X1 = bit (2); // D2 on Uno
const byte X2 = bit (3); // D3 on Uno
const byte X3 = bit (4); // D4 on Uno
const byte patterns [7] [2] = {
// PORT DDR
{ 0, 0, }, // all off
{ X1, X1 | X2 }, // LED1: X1 on, X2 off, X3 HiZ
{ X2, X1 | X2 }, // LED2: X1 off, X2 on, X3 HiZ
{ X2, X2 | X3 }, // LED3: X2 on, X3 off, X1 HiZ
{ X3, X2 | X3 }, // LED4: X2 off, X3 on, X1 HiZ
{ X1, X1 | X3 }, // LED5: X1 on, X3 off, X2 HiZ
{ X3, X1 | X3 }, // LED6: X3 on, X1 off, X2 HiZ
};
void setup ()
{
} // end of setup
void loop ()
{
for (int i = 0; i < 7; i++)
{
DDRD = patterns [i] [1];
PORTD = patterns [i] [0];
delay (500);
} // end of for loop
} // end of loop
</code></pre>
<p>The code displays each of the 6 LEDs (plus all off) in a cycle. For each one it configures the DDR (data direction register) plus the PORT (output register) appropriately to light the desired LED.</p>
<p>It works perfectly, except that you may need to work out which LED is which by experimentation.</p>
|
13493 | |arduino-uno|i2c|digital-analog-conversion| | How do you send data via I2C without the wire library? | 2015-07-16T09:53:48.410 | <p>I have the following digital potentiometer: <a href="http://datasheets.maximintegrated.com/en/ds/DS1803.pdf" rel="nofollow">DS1803-100</a> which, according to the datasheet, can be controlled using a two-wire serial interface. I have managed to get it working using Wire, however I can't seem to get it working using only digitalWrite (<a href="http://pastebin.com/MknvWvjt" rel="nofollow">link to code</a>). Can somebody tell me why? For reference, <strong>0x50</strong> is the <em>address + r/!w bit</em>, <strong>0xA9</strong> is the <em>command (write to pot 0 in my case)</em> and the next <strong>0xA9</strong> is the <em>value to write</em>. I know there's something wrong with the code, however I cannot figure out what. Thank you in advance!</p>
<p>EDIT: Here is the code</p>
<pre><code>int PIN_SCK = 12;
int PIN_SDA = 11;
const int delayvalue = 10;
void setup(){
digitalWrite(PIN_SCK, 1); // I can first declare the state
digitalWrite(PIN_SDA, 1);
pinMode(PIN_SCK, OUTPUT); // then turn them on
pinMode(PIN_SDA, OUTPUT);
delay(1000);
digitalWrite(PIN_SDA, 0); // start bit
shift_out(PIN_SDA, PIN_SCK, 0x50);
shift_out(PIN_SDA, PIN_SCK, 0xA9);
shift_out(PIN_SDA, PIN_SCK, 0xA9);
digitalWrite(PIN_SDA, 1); // stop bit
}
void loop(){
}
// uint8_t is the same as 8 bits aka one byte
void shift_out(uint8_t datapin, uint8_t clockpin, uint8_t val){
uint8_t i;
for (i = 0; i < 8; i++) {
digitalWrite(datapin, !!(val & (1 << (7 - i))));
delay(1);
digitalWrite(clockpin, 0);
delay(delayvalue);
digitalWrite(clockpin, 1);
delay(delayvalue);
}
digitalWrite(datapin, 0); // to enable stop bit
delay(100); // wait fro aknowledgement
}
</code></pre>
| <p>Well, short answer: It was the acknowledge bit, I forgot to send a clock pulse in order to receive it (duh! my device generates the clock for the attached potentiometer, I was waiting for the device to "send" me a bit, I needed to "request" the bit on a rising edge of the clock).</p>
<p>Long answer: the code looks like this now:</p>
<pre><code>int PIN_SCK = 12;
int PIN_SDA = 11;
const int delayvalue = 10;
void setup(){
digitalWrite(PIN_SCK, 1); // I can first declare the state
digitalWrite(PIN_SDA, 1);
pinMode(PIN_SCK, OUTPUT); // then turn them on
pinMode(PIN_SDA, OUTPUT);
delay(1000);
digitalWrite(PIN_SDA, 0); // start bit
delay(10);
digitalWrite(PIN_SCK, 0);
delay(10);
shift_out(PIN_SDA, PIN_SCK, 0x50);
shift_out(PIN_SDA, PIN_SCK, 0xA9);
shift_out(PIN_SDA, PIN_SCK, 0xA9);
digitalWrite(PIN_SDA, 1); // stop bit
}
void loop(){
}
// uint8_t is the same as 8 bits aka one byte
void shift_out(uint8_t datapin, uint8_t clockpin, uint8_t val){
uint8_t i;
for (i = 0; i < 8; i++) {
digitalWrite(datapin, !!(val & (1 << (7 - i))));
delay(1);
digitalWrite(clockpin, 1);
delay(delayvalue);
digitalWrite(clockpin, 0);
delay(delayvalue);
}
digitalWrite(datapin, 0); // to enable stop bit
delay(10);
// Here I handle the AKNOWLEDGE signal which happens after
// each byte sent. Be it address, command or value
digitalWrite(clockpin, 1);
delay(10);
digitalWrite(clockpin, 0);
delay(10);
}
</code></pre>
<p>So basically I followed and reproduced the signals in <a href="https://i.stack.imgur.com/5Kv55.png" rel="nofollow noreferrer">this timing diagram</a> faithfully with one small exception: I did not generate a rising edge when I expected the acknowledge bit (basically the diagram but with SCK being 0 right below the acknowledge bits).</p>
<p>Hope this helps somebody!</p>
|
13499 | |arduino-uno|programming|arduino-due| | Can I Implement a PLL on an Arduino? | 2015-07-16T13:47:35.810 | <p>Is it possible to create a system like a PLL using an Arduino?
I ask this because there are some parts in the PLL system, such as: phase detector, VCO, divider, and I don't know how to make for each part in Arduino board.</p>
| <p>You can absolutely make a PLL using an ATMega microcontroller, and I have made one myself using a ATTiny45. The way I did it is by setting the clock source to the internal RC oscillator, and using that as my VCO (or in this case, Numerically Controlled Oscillator). The internal oscillator can be tuned between 50% and 200% of its nominal frequency by adjusting the OSCCAL register, which can safely be done without stopping the processor. I used the ADC to read the input signal. For the phase detector I programmed the MCU to alternatively add, then subtract the ADC registers from an accumulator register. This is mathematically equivalent to multiplying the incoming signal by a square wave from the local oscillator, and integrating the result. After a fixed number of cycles, I checked to see if the accumulator was negative or positive. If its negative, I set OSCCAL to a "high frequency" which is definitely higher than the input signal. If its positive, I set it to a "low frequency", which is definitely too low. Of course this is a form of Bang–bang control, so its never stable per se, but I found works perfectly. Its much better than my attempts at a PID controller. Looking on my oscilloscope, the is almost no jitter visible between the input system and the internal RC clock, which I outputted on the CLKO pin by setting the appropriate fuse bits.</p>
<p>Although I used GCC and USBTinyISP, I see no reason why my system can't be implemented on Arduino. Setting the fuse bits will require a bit of work though, you can read more here:</p>
<p><a href="http://forum.arduino.cc/index.php?topic=124879.0" rel="nofollow">http://forum.arduino.cc/index.php?topic=124879.0</a></p>
<p>If there is enough interest, I can add more detailed information to my answer.</p>
|
13504 | |arduino-uno|ethernet|hardware| | WizNet chip on Ethernet Shield oddly hot | 2015-07-16T20:35:58.780 | <p>I'm making a thermometer and, so I can graph the data, I have an Uno with the WizNet shield sending the data to a LAN ip. The chip itself is oddly hot, its temperature measures at around <strong>110-120ºF</strong> (43.33-48.89ºC). I want the program to be running almost 24/7. Is it okay for the chip to be this hot?</p>
| <p>According to the <a href="http://wizwiki.net/forum/viewtopic.php?f=20&t=2108&p=6933&hilit=w5100%20temperature#p6933" rel="nofollow">WizNet forums</a> this is normal for these shields. Their justification being that it is a PHY and controller on a single chip. (Note this post only specifically mentions the W5100, which is among the more commonly used chips on these kinds of shields, however, I suspect that this is typical for most of the WizNet line, e.g. W5200 etc.)</p>
|
13512 | |ethernet|web-server| | Arduino web server: redirect to mobile site on SD card? | 2015-07-16T23:30:22.303 | <p>Is there any way to have an Arduino web server redirect the client to a file on the SD card only if the client is using a mobile browser?</p>
<p>(My arduino server is already successfully serving pages on <a href="http://192.168.0.180" rel="nofollow">http://192.168.0.180</a>, and successfully processes GET requests).</p>
<p>I was thinking of having this javascript code on the main page that's served by the arduino:</p>
<pre><code><script type="text/javascript">
<!--
if (screen.width <= 800) {
window.location = "http://192.168.0.180?mobile";
}
//-->
</script>
</code></pre>
<p>My first thought was that maybe it's possible for the server to process that GET request and then serve a page from the SD card, instead of the regular page it serves.</p>
<p>Do you think this is possible, and how would you recommend to do it?</p>
| <p>Yes, it is perfectly possible. you just have to look at the right bits.</p>
<p>Fundamentally there is no difference between an Arduino and any other website, it's just somewhat simpler in how it operates.</p>
<p>All browsers follow the same rules - if they didn't they wouldn't work on the web. Two of the rules you are interested in are:</p>
<ul>
<li>Browsers identify themselves along with their OS.</li>
<li>Browsers respond to the "result" code the website provides in a specific way.</li>
</ul>
<p>Besides the GET request a browser also sends a list of <em>headers</em>. These contain lots of extra information about the request, including the domain name of the website that is being accessed (so the web server knows which site you want - it's not one webserver per site, that would be impractical. For instance, the request to show this page from Firefox on Linux has these headers:</p>
<pre><code>Host: arduino.stackexchange.com
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0 Iceweasel/31.6.0
Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: (I won't bore you with this lot)
Connection: keep-alive
</code></pre>
<p>The header of note is the <em>User-Agent:</em> one. That tells the web server that I am using firefox from a 64-bit Intel Linux computer. If I were to do it from my Android phone it would tell you it's from Chrome on Android. </p>
<p>By looking for that header and parsing it for certain keywords you can find if you're serving to a mobile device or not.</p>
<p>Now the second bullet above - browsers respond to the <em>response</em> code in different ways. Normally you send the response code <code>200</code> which means "I accepted your request and here is the page you asked for". Another response code that is useful is code <code>301</code> which means "The page you asked for isn't at this address any more - here is the new address you should go to instead". That will then cause the browser to go to the newly provided address instead.</p>
<p>So instead of responding with</p>
<pre><code>HTTP/1.0 200 OK
Content-type: text/html
<web page content here>
</code></pre>
<p>You could instead respond with:</p>
<pre><code>HTTP/1.0 301 Moved Permanently
Location: http://myarduino.local/mobile
</code></pre>
<p>And the browser will <em>redirect</em> to the new address you give in the <em>Location:</em> response header.</p>
<p>The full list of response codes is here: <a href="https://en.wikipedia.org/wiki/List_of_HTTP_status_codes" rel="nofollow">https://en.wikipedia.org/wiki/List_of_HTTP_status_codes</a></p>
<p>If you want to avoid the overhead of a browser redirect you can just serve different data to the browser depending on what the User-Agent header specifies. After all, it's entirely down to you what is sent as the content of the page. Whether you get that from purely programmatical means, or by reading a file off an SD card, is entirely up to you.</p>
|
13518 | |pwm|timers|millis| | Adjust time calculation after Timer0 frequency change | 2015-07-17T06:06:14.653 | <p>I have an Arduino Nano with an 328P and need all 6 PWM pins.</p>
<p>Thus, I had to adjust the prescaler and WGM Mode of Timer0.</p>
<p>It is now in phase correct PWM mode with a prescaler of 1.</p>
<pre><code>TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM00);
TCCR0B = _BV(CS00);
</code></pre>
<p>Now I need a working time calculation for other libraries, but since
Timer0 had that duty everything is out of order now.</p>
<p>I tried adjusting the wiring.c </p>
<pre><code>// the prescaler is set so that timer0 ticks every 64 clock cycles, and the
// the overflow handler is called every 256 ticks.
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))
</code></pre>
<p>to this</p>
<pre><code>#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(1 * 510))
</code></pre>
<p>But it's like I didn't change anything.
(tested other settings that <strong>were changed</strong> so it was compiled anew )</p>
<p>Whole Code:</p>
<pre><code>void setup() {
// Set Timer 0, 1 and 2
// Register A: Output A and B to non-inverted PWM and PWM mode to phase correct.
// Register B: Pre Scaler to 1.
TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM00);
TCCR0B = _BV(CS00);
TCCR1A = _BV(COM1A1) | _BV(COM1B1) | _BV(WGM10);
TCCR1B = _BV(CS10);
TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM20);
TCCR2B = _BV(CS20);
pinMode(8, OUTPUT);
}
void loop() {
digitalWrite(8, LOW);
delay(65000);
digitalWrite(8, HIGH);
delay(65000);
}
</code></pre>
| <p>Thanks to Edgar's answer and Nebsie's explaination on how the counter exactly works I could come up with my own implementation of how to rectify delay and micros() that - so far - seems to work fine on my Arduino Uno.</p>
<p>I'm not saying that this is the most precise implementation, especially I have my doubts on micros() if for example an timer overflow occours between reading t1 and t2, but it is one that so far for me works well. </p>
<p>First thing - according to Edgar's recommendation I defined:</p>
<pre><code>#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(1 * 512))
</code></pre>
<p>However this doesn't affect timing of micros() or delay().</p>
<p>Function micros() I changed to read two times from TCNT0 - to determine whether it is counting upwards or downwards. This is done with the "if (t1 > t2)" clause. The overflow count "m" is multiplied by 510, because the counter elapses after 510 steps. Then the calculated counter value "t" is added to this, divided by the number of clocks per Microsecond. (Note: Prescaler = 1, therefore no further multplication).</p>
<pre><code>unsigned long micros() {
unsigned long m;
uint8_t oldSREG = SREG, t1, t2;
uint16_t t;
cli();
m = timer0_overflow_count;
#if defined(TCNT0)
t1 = TCNT0;
#elif defined(TCNT0L)
t1 = TCNT0L;
#else
#error TIMER 0 not defined
#endif
#if defined(TCNT0)
t2 = TCNT0;
#elif defined(TCNT0L)
t2 = TCNT0L;
#else
#error TIMER 0 not defined
#endif
if (t1 >= t2) {
t = 510 - t2; // counter running backwards
} else {
t = t2; // counter running upwards
}
#ifdef TIFR0
if ((TIFR0 & _BV(TOV0)) && (t2 > 1)) // if overflow flag is set -> increase m
m++;
#else
if ((TIFR & _BV(TOV0)) && (t2 > 1))
m++;
#endif
SREG = oldSREG;
return ((m * 510) + t) / clockCyclesPerMicrosecond();
}
</code></pre>
<p>HOWEVER - this seems to work fine but I had issues to begin with (before editing this again). Due to the counter running much faster, every 268 seconds the unsigned long datatype of micros() overflows and starts from zero again. This led to an unwanted lockup of delay(), especially if long delay times, like in my case delays of one second per loop iterations are used. Therefore I also had to add an overflow detection to the delay() function in arduino wiring.c.</p>
<p>If the overflow occurs, timing might not be very precise. But since this is once overy 268 seconds it may be acceptable. So far with this change the delay function works fine again on my side. </p>
<pre><code>void delay(unsigned long ms)
{
uint32_t start = micros();
uint32_t elapsed = 0;
while (ms > 0) {
yield();
while ( ms > 0 && (micros() - 1000) >= (start + elapsed)) {
ms--;
elapsed += 1000;
}
if( start > micros() ) { // overflow detected
start = micros(); // reset start
elapsed = 0; // reset elapsed
}
}
}
</code></pre>
|
13522 | |arduino-uno|analogread| | Can I use analogRead to read a digital pin? | 2015-07-17T11:11:00.183 | <p>analogRead(nGPIO_max + lockerVal) were nGPIO_max(maximum digital pins in Arduino Uno is 13) and lockerval is 2. Which pin is it reading? </p>
| <p>To answer the question in the title: No, you cannot use <code>analogRead()</code> to read a digital pin. A digital pin cannot behave as analog because it isn't connected to the ADC (Analog to Digital Converter).</p>
<p>If you call something equating to <code>analogRead(15)</code> on an Uno, then it should read pin <code>A1</code>. You can see the pin assignments in the board-specific versions of <code>pins_arduino.h</code> (shipped with the IDE):</p>
<pre><code>static const uint8_t A0 = 14;
static const uint8_t A1 = 15;
static const uint8_t A2 = 16;
static const uint8_t A3 = 17;
static const uint8_t A4 = 18;
static const uint8_t A5 = 19;
static const uint8_t A6 = 20;
static const uint8_t A7 = 21;
</code></pre>
<p>Using those raw numbers directly is generally not a good idea though as it obscures your code's meaning, and will potentially make it non-portable to other boards. It's better to call something like <code>analogRead(A1)</code>.</p>
<p>It's worth noting that the Arduino library fudges the pin numbers slightly. Calling <code>analogRead(1)</code> has the same result as calling <code>analogRead(A1)</code>. That means that even if you <em>tried</em> to use <code>analogRead()</code> on a digital pin, it might actually end up reading an analog pin instead. Alternatively, it might just return a meaningless result, depending on the pin number you give it.</p>
|
13528 | |programming|arduino-mega|shields| | Arduino Web Server and Relay Module | 2015-07-17T16:45:45.830 | <p>I am working on a web server project for work. I have a web server setup with an Arduino Meg2560 with Ethernet. I also have a 16 relay board connected to Ethernet with its own IP. I wanted to see if there is a way I can make calls to the relay board via IP from the Arduino Webserver. For example Relay 1 on the relay board can be turned on by typing 192.168.1.4/30000/00 but this opens the web GUI on the board. I need to do the same thing but without opening the webpage or web GUI.
<img src="https://i.stack.imgur.com/dzZjs.jpg" alt="enter image description here"></p>
<pre><code> #include <SPI.h>
#include <Ethernet.h>
// MAC address from Ethernet shield sticker under board
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 177); // IP address
EthernetServer server(80); // Server Port 80
void setup()
{
Ethernet.begin(mac, ip);
server.begin();
}
void loop()
{
EthernetClient client = server.available(); // try to get client
if (client) { // got client?
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) { // client data available to read
char c = client.read(); // read 1 byte (character) from client
// last line of client request is blank and ends with \n
// respond to client only after last line received
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close");
client.println();
// send web page
client.println("<!DOCTYPE html>");
client.println("<html>");
client.println("<head>");
client.println("<title>Arduino Web Page</title>");
client.println("</head>");
client.println("<body>");
client.println("<h1>Hello from Arduino!</h1>");
client.println("<p>A web page from the Arduino server</p>");
client.println("</body>");
client.println("</html>");
break;
}
// every line of text received from the client ends with \r\n
if (c == '\n') {
// last character on line of received text
// starting new line with next character read
currentLineIsBlank = true;
}
else if (c != '\r') {
// a text character was received from client
currentLineIsBlank = false;
}
} // end if (client.available())
} // end while (client.connected())
delay(1); // give the web browser time to receive the data
client.stop(); // close the connection
} // end if (client)
</code></pre>
<p>}</p>
| <p>Documentation on the <a href="http://www.sainsmart.com/sainsmart-ethernet-control-module-lan-wan-web-server-control-with-rj45-port.html" rel="nofollow">controller</a> you are using is pretty scant, but it looks like you just need to make a GET request to the URI corresponding to the action you need to take.</p>
<blockquote>
<p><a href="http://192.168.1.4/30000/00" rel="nofollow">http://192.168.1.4/30000/00</a> : Relay-01 OFF</p>
<p><a href="http://192.168.1.4/30000/01" rel="nofollow">http://192.168.1.4/30000/01</a> : Relay-01 ON</p>
<p><a href="http://192.168.1.4/30000/02" rel="nofollow">http://192.168.1.4/30000/02</a> : Relay-02 OFF</p>
<p><a href="http://192.168.1.4/30000/03" rel="nofollow">http://192.168.1.4/30000/03</a> : Relay-02 ON</p>
<p><a href="http://192.168.1.4/30000/04" rel="nofollow">http://192.168.1.4/30000/04</a> : Relay-03 OFF</p>
<p><a href="http://192.168.1.4/30000/05" rel="nofollow">http://192.168.1.4/30000/05</a> : Relay-03 ON</p>
<p>…</p>
<p><a href="http://192.168.1.4/30000/14" rel="nofollow">http://192.168.1.4/30000/14</a> : Relay-8 OFF</p>
<p><a href="http://192.168.1.4/30000/15" rel="nofollow">http://192.168.1.4/30000/15</a> : Relay-8 ON</p>
<p><a href="http://192.168.1.4/30000/41" rel="nofollow">http://192.168.1.4/30000/41</a> : Enter</p>
<p><a href="http://192.168.1.4/30000/40" rel="nofollow">http://192.168.1.4/30000/40</a> : Exit</p>
<p><a href="http://192.168.1.4/30000/42" rel="nofollow">http://192.168.1.4/30000/42</a> : Next Page</p>
<p><a href="http://192.168.1.4/30000/43" rel="nofollow">http://192.168.1.4/30000/43</a> : Next Page</p>
</blockquote>
<p>For example If I wanted to turn off relay 3, I would simple make a GET request to <code>http://192.168.1.4/30000/04</code> and close the connection. Example code:</p>
<pre><code>IPAddress server(192,168,1,4);
EthernetClient client;
client.connect(server, 80);
client.println("GET /30000/04 HTTP/1.1");
client.println("Connection: close");
client.println();
client.stop();
</code></pre>
|
13535 | |pwm|timers|avr| | PWM timers, channels and pins | 2015-07-18T06:02:35.913 | <p>I've got this code from the <a href="http://www.multiwii.com/" rel="nofollow">MultiWii</a> project, which is relevant to the hardware, <a href="http://www.atmel.com/devices/ATMEGA32U4.aspx" rel="nofollow">ATmega32u4</a>, I have. It is part of a function called <code>initOutput()</code>.</p>
<p>In the comment it says "connect pin 6", which is the bit of that which specifies pin 6 as I would like to change it to another pin, specifically A0.</p>
<pre><code>// Enhanced PWM mode
TCCR4E |= (1<<ENHC4);
// Prescaler to 16
TCCR4B &= ~(1<<CS41);
TCCR4B |= (1<<CS42) | (1<<CS40);
// Phase and frequency correct mode and top to 1023, but
// with enhanced PWM mode we have 2047.
TCCR4D |= (1<<WGM40);
TC4H = 0x3;
OCR4C = 0xFF;
// Connect pin 6 to timer 4 channel D
TCCR4C |= (1<<COM4D1) | (1<<PWM4D);
</code></pre>
| <p>It's the <code>(1<<COM4D1)</code> that enables pin 6, or more specifically <strong>OC4D</strong> for timer output. You cannot use A0 instead, since there is no output compare capability on that pin; only pins 13, 5, 10, 9, 6, and 12 can be connected to timer 4. See the datasheet for details.</p>
|
13538 | |lcd|pins| | Can I connect TFT LCD screen to Arduino Leonardo same way as it's recommanded for Arduino Uno? | 2015-07-18T13:39:50.557 | <p>I want to connect the <em>Arduino TFT LCD 1.77" screen</em> to an <em>Arduino Leonardo</em>. Acording to <a href="https://www.arduino.cc/en/Guide/TFTtoBoards" rel="nofollow">this</a> tutorial I should connect some pins on LCD screen to <em>ICSP pins</em> on Leonardo but I don't have equipment to do it. Can I just connect LCD screen to Leonardo in the way it't recommanded for an <em>Arduino Uno</em> (same tutorial above) using only digital and power pins. And then use sketches for Uno. Will it work?</p>
<p>Also, is it safe for LCD screen?</p>
| <p>You can hook up the "Adafruit_ST7735" or from what i later learned after getting my Esplora. Thats when i had my adruino-epiphany. Okay so IF your wondering why im including this super rad Controller shaped arduino, the answer is, its a leonardo. well its just a different flavor of the Atmega32u4 whis is the chip that made ext serial programmers kinda obsolete and makes the uno and megas so unique as well. so with that being said the Esplora has a native language when refering back the tft libraries, but its not too far from a simple (ctrl+F) and replace Esplora references with actual defines and references. and in this case the Leonardo would need to have the icsp header used by the corresponding pins on the display (for this instance of using an SPI connection with the serial display we will not swap the Miso and Mosi like we would a nother instance.just connect miso to miso and mosi to mosi i usually plug up the whole icsp header and then that wwill leave you with the two pins you MUST DEFINE to make it work which would be :</p>
<pre><code>// Pins SCLK and MOSI are fixed in hardware, and pin 10 (or 53)
</code></pre>
<p>// must be an output
//#define sclk 13 // for MEGAs use pin 52
//#define mosi 11 // for MEGAs use pin 51</p>
<h1>define cs 10 // for MEGAs you probably want this to be pin 53</h1>
<h1>define dc 9</h1>
<h1>define rst 8 // you can also connect this to the Arduino reset</h1>
<pre><code>// Pins SCLK and MOSI are fixed in hardware, and pin 10 (or 53)
</code></pre>
<p>// must be an output
//#define sclk 13 // for MEGAs use pin 52
//#define mosi 11 // for MEGAs use pin 51</p>
<h1>define cs 10 // for MEGAs you probably want this to be pin 53</h1>
<h1>define dc 9</h1>
<h1>define rst 8 // you can also connect this to the Arduino reset</h1>
<p>// Color definitions</p>
<h1>define BLACK 0x0000</h1>
<h1>define BLUE 0x001F</h1>
<h1>define RED 0xF800</h1>
<h1>define GREEN 0x07E0</h1>
<h1>define CYAN 0x07FF</h1>
<h1>define MAGENTA 0xF81F</h1>
<h1>define YELLOW 0xFFE0</h1>
<h1>define WHITE 0xFFFF</h1>
<h1>include </h1>
<h1>include </h1>
<p>// Option 1: use any pins but a little slower
//ST7735 tft = ST7735(cs, dc, mosi, sclk, rst); </p>
<p>// Option 2: must use the hardware SPI pins
// (for UNO thats sclk = 13 and sid = 11) and pin 10 must be
// an output. This is much faster - also required if you want
// to use the microSD card (see the image drawing example)
ST7735 tft = ST7735(cs, dc, rst);
float p = 3.141592; // value for pi
int tft_width = 128;
int tft_height = 160;
int x1 = 60;
int y1 = 60;
int x2 = 20;
int y2 = 80;
int ballx = 60;
int bally = 60;
int deltay = 1;
int deltax = 1;</p>
<p>int ball_speed = 24;</p>
<p>int left_score = 4;
int right_score = 4;</p>
<p>int background_color = 0x00;
void setup(void) {
tft.initR(); // initialize a ST7735R chip</p>
<p>tft.writecommand(ST7735_DISPON);
tft.fillScreen(background_color);
delay(700);
for(int i = 0; i < 9; i++){
pinMode(i,OUTPUT);
}
for(int i = 0; i < 9; i++){
digitalWrite(i,HIGH);
}
delay(500);</p>
<p>}</p>
<p>void loop() {<br>
for(int i = 0; i < left_score; i++){
digitalWrite(i,HIGH);
}
for(int i = 0; i < right_score; i++){
digitalWrite(i+4,HIGH);
}
int cur_r = random(20,32);
int cur_g = random(55,64);
int cur_b = random(10,32);
int color = cur_r | (cur_g << 5) | (cur_b << 11);
int radius = 4;
draw_paddles();
draw_ball(color);
delay(ball_speed);
}
void draw_input_text(){
int cur_x2 = analogRead(2);
int cur_y2 = analogRead(3);<br>
String xs = String(cur_x2);
String ys = String(cur_y2);
char cx[4];
cx[0] = xs.charAt(0);
cx[1] = xs.charAt(1);
cx[2] = xs.charAt(2);
cx[3] =0;
char cy[4];
cy[0] = ys.charAt(0);
cy[1] = ys.charAt(1);
cy[2] = ys.charAt(2);
cy[3] =0;
tft.fillRect(10,20,40,40,background_color);
tft.drawString(12,22,cx ,YELLOW);
tft.drawString(12,40,cy ,YELLOW);
}
void draw_paddles(){
int cur_x = analogRead(0);
int cur_y = analogRead(1);<br>
int hval = 620;
int lval = 350;</p>
<p>if ( y1 < tft_height - 20 && cur_y > hval) y1++;
else if ( y1 > 0 && cur_y < lval ) y1--; </p>
<p>int cur_x2 = analogRead(2);
int cur_y2 = analogRead(3); </p>
<p>if ( y2 < tft_height - 20 && cur_y2 > hval ) y2++;
else if (y2 > 0 && cur_y2 < lval ) y2--;
tft.fillRect(2, y1-3, 5, 27, background_color);
tft.fillRect(3, y1, 3, 20, YELLOW);
tft.fillRect(tft_width-3, y2-3, 5, 27,background_color);
tft.fillRect(tft_width-3, y2, 3, 20, YELLOW);
}
void draw_ball(int color){
int bradius = 6;
tft.fillCircle(ballx, bally, bradius , color);
ballx += deltax;
bally += deltay;
if ( ballx < 7 && bally > y1 && bally < y1+20) deltax *= -1;
else if ( ballx > tft_width-7 && bally > y2 && bally < y2+20) deltax *= -1;
else if ( bally <= bradius || bally >= tft_height - bradius ) deltay *= -1;
if (ballx <= 0 ) {
left_score--;
tft.drawString(2,42, "Right Won!" ,~background_color,2);
tft.drawString(2,62, "Get Ready!" ,CYAN,2);
for (int i = 0; i <250; i++){
delay(10);
draw_paddles();
}
int cur_r = random(0,26);
int cur_g = random(0,30);
int cur_b = random(0,18);
background_color = cur_r | (cur_g << 5) | (cur_b << 11);
tft.fillScreen(background_color);
ballx = 64;
bally = 80;
if (ball_speed > 1) ball_speed--;
digitalWrite(left_score,LOW);
} else if (ballx >= tft_width ) {
right_score --;
tft.drawString(2,42, "Left Won!" ,YELLOW,2);
tft.drawString(2,62, "Get Ready!" ,GREEN,2);
for (int i = 0; i <250; i++){
delay(10);
draw_paddles();
}
int cur_r = random(0,26);
int cur_g = random(0,30);
int cur_b = random(0,18);
background_color = cur_r | (cur_g << 5) | (cur_b << 11);
tft.fillScreen(background_color);
ballx = 64;
bally = 80;
if (ball_speed > 1) ball_speed--;</p>
<pre><code> digitalWrite(4+right_score,LOW);
}
</code></pre>
<p>}</p>
<p>enjoy getting that code to fudge around with i stole it right form here <a href="http://lucidtronix.com/tutorials/7" rel="nofollow">http://lucidtronix.com/tutorials/7</a>
but the point i had to bring up is that i believe the guy before mentioned that it is a muchslower connectionor process than if it were.....were you saying softwareserial was the option then?
because im not an explert or novice or maker by any means. but i have picked up along the lines that hardware serial will always trump software serial compilation any day once you get your head wrapped around the brevity of what ports and pins are actually what are used or have the data displayed on the serial ports. and like software is a necessity im afraid, but its as simple as reasigning pins and when that gets too hard going out and just bbuying a mega, haahah hope i sorta helped. id say go out and snag an esplora whilst their like toing a fire clearance sale on the originallt 50$+ boards. but their reference and prebuilt array of sensors is a bit underwhelming for the newbies in what it alll does, but kinda overwhelmine and difficult to transistion onece having looked at some code as it is, but the language is more forg9ving, but i believe their also officially retiring the leonardo espolora and micro series so good luck this tft display kicks bum man and is the only one that hsnt broke</p>
|
13545 | |flash|progmem|struct| | Using PROGMEM to store array of structs | 2015-07-18T18:37:54.267 | <p>I am hitting the limits of my arduino's SRAM and found that SRAM usage can be reduced by storing static stuff in flash memory instead of SRAM.</p>
<p>My project can (optionally) be built with an included SimulatorClass. I use this to 'playback' data at home which I gathered during real-life testing of my project. My project is based on photoelectric sensors, and it's timing-critical, so all timekeeping is done using <code>micros()</code>, which returns <code>unsigned long</code> datatype.</p>
<p>To simulate these photoelectric sensor triggers, I need an array containing a <code>struct</code> of 3 variables each:
unsigned int _iDataPos;</p>
<pre><code> struct SimulatorRecord
{
uint8_t iSensorNumber;
unsigned long lTriggerTime;
uint8_t iState;
};
</code></pre>
<p>So one these structs is 6 bytes long in my counting (2x <code>uint8_t</code> = 2 bytes, <code>unsigned long</code> = 4 bytes).
A typical set of simulator records I need to use is about 25-30 records long, so worst case scenario the simulator array is 180 bytes in size.</p>
<p>I initialize these arrays like so:</p>
<pre><code>SimulatorRecord SimulatorQueue[28] = {
{ 1, 41708, 1 }
, { 2, 60692, 1 }
, { 1, 176848, 0 }
, { 2, 197732, 0 }
, { 1, 4675580, 1 }
, { 2, 4692252, 1 }
, { 2, 4830180, 0 }
, { 1, 4849032, 0 }
, { 2, 9058416, 1 }
, { 1, 9074780, 1 }
, { 1, 9215868, 0 }
, { 2, 9234968, 0 }
, { 2, 13497276, 1 }
, { 2, 13500924, 0 }
, { 2, 13502728, 1 }
, { 1, 13514992, 1 }
, { 1, 13668000, 0 }
, { 1, 13669344, 1 }
, { 1, 13681828, 0 }
, { 2, 13701464, 0 }
, { 2, 18028788, 1 }
, { 2, 18034252, 0 }
, { 2, 18036540, 1 }
, { 1, 18046892, 1 }
, { 2, 18160312, 0 }
, { 1, 18178224, 0 }
, { 1, 20454580, 1 }
, { 1, 20456368, 0 }
};
</code></pre>
<p>In my simulator code I then loop through these arrays like so:</p>
<pre><code> unsigned int _iDataPos = 0;
SimulatorRecord PendingRecord = SimulatorQueue[_iDataPos];
//main simulator loop
if (PendingRecord.lTriggerTime <= lRaceElapsedTime)
{
//simulate signal
digitalWrite(PendingRecord.iSensorNumber, PendingRecord.iState);
//And increase pending record
_iDataPos++;
PendingRecord = SimulatorQueue[_iDataPos];
}
</code></pre>
<p>Now I've been reading various <code>PROGMEM</code> tutorials, and storing the <code>SimulatorQueue</code> array in flash seems to be piece of cake, just change</p>
<pre><code>SimulatorRecord SimulatorQueue[28]
</code></pre>
<p>to</p>
<pre><code>const PROGMEM SimulatorRecord SimulatorQueue[28]
</code></pre>
<p>But for the life of me I can't find out how I should change the copying of each array item to the <code>PendingRecord</code> variable, as my <code>iDataPos</code> counter increases.</p>
<p>Edit: I should have mentioned that this simulator class and all it's member functions & variables reside in a seperate *.cpp and *.h file.
I alreadt found out that since i'm initializing the <code>SimulatorQueue</code> array in the class itself, and not in the main *.ino file, I should do it like so:</p>
<pre><code>constexpr static SimulatorRecord SimulatorQueue[28] PROGMEM = {<structs go in here>};
</code></pre>
<p>Edit2: Sample code which reproduces the problem when the simulator array is available here:
<a href="http://1drv.ms/1TRwiIB" rel="noreferrer">http://1drv.ms/1TRwiIB</a></p>
|
<p>An easy way of accessing any type of data in PROGMEM is to use this small library:</p>
<p><strong>PROGMEM_readAnything.h</strong></p>
<pre class="lang-C++ prettyprint-override"><code>#include <Arduino.h> // for type definitions
template <typename T> void PROGMEM_readAnything (const T * sce, T& dest)
{
memcpy_P (&dest, sce, sizeof (T));
}
template <typename T> T PROGMEM_getAnything (const T * sce)
{
static T temp;
memcpy_P (&temp, sce, sizeof (T));
return temp;
}
</code></pre>
<p>You can put that file into a new tab in your IDE, or make a library by putting it inside a folder called <code>PROGMEM_readAnything</code> and put that folder inside the <code>libraries</code> folder, which is inside your sketchbook folder.</p>
<p>That lets you copy from the memory in PROGMEM (using memcpy_P) into RAM. The template is used to work out how many bytes to copy.</p>
<hr>
<p>Example, using your structure:</p>
<pre class="lang-C++ prettyprint-override"><code>#include <PROGMEM_readAnything.h>
struct SimulatorRecord
{
uint8_t iSensorNumber;
unsigned long lTriggerTime;
uint8_t iState;
};
const SimulatorRecord SimulatorQueue[28] PROGMEM = {
{ 1, 41708, 1 }
, { 2, 60692, 1 }
, { 1, 176848, 0 }
// ... omitted for brevity
, { 1, 18178224, 0 }
, { 1, 20454580, 1 }
, { 1, 20456368, 0 }
};
// number of items in an array
template< typename T, size_t N > size_t ArraySize (T (&) [N]){ return N; }
void setup ()
{
Serial.begin (115200);
Serial.println ();
for (int i = 0; i < ArraySize (SimulatorQueue); i++)
{
SimulatorRecord thisItem;
PROGMEM_readAnything (&SimulatorQueue [i], thisItem);
Serial.print (i);
Serial.print (F(" = "));
Serial.print (thisItem.iSensorNumber);
Serial.print (F(" / "));
Serial.print (thisItem.lTriggerTime);
Serial.print (F(" / "));
Serial.print (thisItem.iState);
Serial.println ();
} // end of for loop
} // end of setup
void loop ()
{
} // end of loop
</code></pre>
<p>I found that it decreased RAM usage by 166 bytes, which is almost <code>28 * 6</code> (a couple of bytes must have been used by something).</p>
<hr>
<h3>Reference</h3>
<p><a href="http://www.gammon.com.au/progmem" rel="noreferrer">Putting constant data into program memory (PROGMEM)</a></p>
<hr>
<h3>Putting PROGMEM into a class</h3>
<p>In response to some comments below, this explains how to put the constants into a class.</p>
<p>Alex originally had:</p>
<pre class="lang-C++ prettyprint-override"><code>class SimulatorClass
{
...
typedef struct SimulatorRecord
{
uint8_t iSensorNumber;
unsigned long lTriggerTime;
uint8_t iState;
} SimulatorRecord;
constexpr static SimulatorRecord SimulatorQueue[28] PROGMEM = {
{ 1, 41708, 1 }
, { 2, 60692, 1 }
// ... omitted for brevity
, { 1, 20454580, 1 }
, { 1, 20456368, 0 }
};
SimulatorRecord PendingRecord;
};
</code></pre>
<p>Putting aside whatever "constexpr" is, you can't put constants inside a class like that. You need to make it static, and have the actual definition elsewhere. So, change the constants to:</p>
<pre class="lang-C++ prettyprint-override"><code>class SimulatorClass
{
...
typedef struct SimulatorRecord
{
uint8_t iSensorNumber;
unsigned long lTriggerTime;
uint8_t iState;
} SimulatorRecord;
static const SimulatorRecord SimulatorQueue[28] PROGMEM ;
SimulatorRecord PendingRecord;
};
</code></pre>
<p>Now in your main class file (Simulator.cpp in your case):</p>
<pre class="lang-C++ prettyprint-override"><code> const SimulatorClass::SimulatorRecord SimulatorClass::SimulatorQueue[28] PROGMEM = {
{ 1, 41708, 1 }
, { 2, 60692, 1 }
// ... omitted for brevity
, { 1, 20454580, 1 }
, { 1, 20456368, 0 }
};
</code></pre>
<p>That now compiles OK.</p>
|
13551 | |c++|lcd| | Arduino uint8_t to String or char- retrieve from usb device | 2015-07-18T18:44:27.037 | <p>My code returns uint8_t format when is cast to char and Display on LCD it works fine but I want to get that scanned code for further processing. not only to display on LCD 16x2 , but it returns some strange symbols. Any Idea?</p>
<pre><code>#include <LiquidCrystal.h>
#include <avr/pgmspace.h>
#include <hid.h>
#include <hiduniversal.h>
#include <usbhub.h>
#include <Usb.h>
#include <usbhub.h>
#include <avr/pgmspace.h>
#include <hidboot.h>
#include <SPI.h>
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
USB Usb;
USBHub Hub(&Usb);
HIDUniversal Hid(&Usb);
HIDBoot<HID_PROTOCOL_KEYBOARD> Keyboard(&Usb);
class KbdRptParser : public KeyboardReportParser
{
void PrintKey(uint8_t mod, uint8_t key);
protected:
virtual void OnKeyDown (uint8_t mod, uint8_t key);
virtual void OnKeyPressed(uint8_t key);
};
void KbdRptParser::OnKeyDown(uint8_t mod, uint8_t key)
{
uint8_t c = OemToAscii(mod, key);
if (c)
OnKeyPressed(c);
}
/* what to do when symbol arrives */
void KbdRptParser::OnKeyPressed(uint8_t key)
{
static uint32_t next_time = 0; //watchdog
static uint8_t current_cursor = 0; //tracks current cursor position
if( millis() > next_time ) {
lcd.clear();
current_cursor = 0;
delay( 5 ); //LCD-specific
lcd.setCursor( 0,0 );
}//if( millis() > next_time ...
next_time = millis() + 200; //reset watchdog
if( current_cursor++ == ( DISPLAY_WIDTH + 1 )) { //switch to second line if cursor outside the screen
lcd.setCursor( 0,1 );
}
char keys=(char) key;
Serial.println(keys);
// char add =keys.indexOf(5)+keys.indexOf(6)+keys.indexOf(7)+keys.indexOf(8);
Serial.println(keys);
lcd.print(keys);
};
KbdRptParser Prs;
void setup()
{
Serial.begin( 115200 );
Serial.println("Start");
if (Usb.Init() == -1) {
Serial.println("OSC did not start.");
}
delay( 200 );
Hid.SetReportParser(0, (HIDReportParser*)&Prs);
// set up the LCD's number of columns and rows:
lcd.begin(DISPLAY_WIDTH, 2);
lcd.clear();
lcd.noAutoscroll();
lcd.print("Scan Your Code");
delay( 200 );
}
void loop()
{
Usb.Task();
}
</code></pre>
| <p>If the symbols look like Japanese, then probably bit 7 of your characters is set to 1. The upper 128 characters are reserved for Katakana in many LCDs. So, if you are sure the characters are correct, you may have to be AND them with 0x7F to assure they are in the right half of the character encoder.</p>
<p>Do check the requirements of your LCD, and the code in the library to control the display. In one occasion, you added a 5 ms delay, and in other clear(), you didn't. One of the annoyances of LCD displays is that you have to be careful with those delay, else you can land the controller in a strange mode,</p>
|
13557 | |pwm|timers|avr| | 32u4 timer 4 pwm frequency help | 2015-07-19T02:06:35.373 | <p>I have extracted the following code from the multiwii project. It generates a ~490-500hz pwm signal on pin 6 which is used to drive an esc.</p>
<p>I want to change this frequency down to 50Hz to drive a servo instead. But ive had next to no experience at this level of avr programming, and dont want to loose anymore days to it, if its a dead end. (ie not possible) (i have tried reading various websites on the topic)</p>
<pre><code>void setup() {
pinMode(6, OUTPUT);
TCCR4E |= (1<<ENHC4); // enhanced pwm mode
TCCR4B &= ~(1<<CS41); TCCR4B |= (1<<CS42)|(1<<CS40); // prescaler to 16
TCCR4D |= (1<<WGM40); TC4H = 0x3; OCR4C = 0xFF; // phase and frequency correct mode & top to 1023 but with enhanced pwm mode we have 2047
TCCR4C |= (1<<COM4D1)|(1<<PWM4D); // connect pin 6 to timer 4 channel D
}
void loop() {
//write out
int value = 1500;
TC4H = value>>8;
OCR4D = (value&0xFF);
}
</code></pre>
<p>here is the new code so far working off the solution provided below:</p>
<pre><code>void setup() {
pinMode(6, OUTPUT);
TCCR4B &= ~(_BV(CS43) | _BV(CS42) | _BV(CS41) | _BV(CS40));
TCCR4B |= _BV(CS43) | _BV(CS41);
TCCR4D &= ~(_BV(WGM41) | _BV(WGM40));
TC4H = 624 >> 8; // B10 0x2
OCR4C = 624 & 0xff;//B1110000 0x70
TCCR4C |= (1<<COM4D1)|(1<<PWM4D);
}
void loop() {
//write out
//30 - 60 gives 1000 to 2000 us, but that only allows 30 increments between ??
int value = 30;
TC4H = value >> 8;
OCR4D = value & 0xff;
}
</code></pre>
<p>the wave form i want:</p>
<p><img src="https://i.stack.imgur.com/f1BEv.png" alt="the wave form i want"></p>
| <p>To get finer resolution use Timer 1 - as Ignacio Vazquez-Abrams suggested.</p>
<pre><code>void setup ()
{
pinMode (10, OUTPUT); // OC1B on the Leonardo / Micro
TCCR1A = 0; // stop Timer 1
TCCR1B = 0; // ditto
// set up Timer 1
TCCR1A = bit (COM1B1) | bit (WGM11) | bit (WGM10); // toggle OC1B on Compare Match
TCCR1B = bit (WGM13) | bit (CS11); // PWM phase correct, prescaler of 8
OCR1A = 20000; // frequency: 50 Hz
OCR1B = 1000; // duty cycle - 1 ms
} // end of setup
void loop ()
{
// whatever
} // end of loop
</code></pre>
<p>As you can see from the scope output, the pulse width is 1 ms, which extremely conveniently corresponds to the duty cycle of 1000. Thus, therefore, the duty cycle figure is exactly related to microseconds.</p>
<p>Also you can see that the frequency is 50 Hz.</p>
<p><img src="https://i.stack.imgur.com/kFOiZ.png" alt="50 Hz Timer 1 example"></p>
<p>This uses a prescaler of 8 to give high resolution. It takes two pulses to make one "cycle" (one on, one off) and thus it effectively divides the system clock by 16. Since the system clock is 16 MHz, that is why one "unit" is 1 µs.</p>
<p>The OCR1A figure is arrived at easily:</p>
<pre><code> 1000000 / 50 = 20000 (1 MHz / 50 Hz)
</code></pre>
<p>Now you can just tweak your desired pulse width knowing that each unit is 1 µs. So for 2 ms OCR1B would need to be 2000.</p>
|
13566 | |bluetooth| | Set Bluno Beetle to Broadcast mode | 2015-07-19T10:22:52.887 | <p>I recently purchased Bluno Beetle (basically a smaller Arduino with a BLE chip). It is based on the Bluno: <a href="http://www.dfrobot.com/wiki/index.php/Bluno_SKU:DFR0267#Wireless_Programming_via_BLE" rel="nofollow">Wiki</a> I know that its Bluetooth Chip, the TI CC2540, supports the Broadcast mode: <a href="http://www.ti.com/product/CC2540/description" rel="nofollow">Official page</a></p>
<p>However I can't find any <a href="http://www.dfrobot.com/wiki/index.php/Bluno_SKU:DFR0267#AT_Command_List" rel="nofollow">AT commands</a> that would allow me to set it to this mode, does anyone of you have an idea? I am trying to relay the messages they are sending (sensor readings), essentially building an interconnected network.</p>
| <p>It looks like the Bluno only supports the Central and Peripheral roles (i.e. not the Broadcaster and Observer roles.) Keep in mind AT commands are a feature of the firmware, not the actual chip. As such, even if the chip supports a particular mode or role, that doesn't necessarily mean the firmware makes the feature available.</p>
|
13571 | |power|arduino-due|usb| | How to disable Due USB power? | 2015-07-19T15:33:49.600 | <p>I need my Arduino Due to work only from external power supply, not from USB power. Is there any way to modify the circuit to allow this? I still need to keep USB communication, but it should happen only when external power is on. Thanks</p>
| <p>There is four ways I know of you can do to achieve exactly this :</p>
<ul>
<li>You can remove the usb polyfuse from your board, which will make the usb behave exactly as you need it to. Between the 2 <a href="https://www.arduino.cc/en/uploads/Main/ArduinoDue_Front.jpg" rel="nofollow">two usb connections in this picture </a> is a smd component marked 501V. This is your polyfuse. Disabling this cuts the +5v line to the board from the usb but leaves the data lines open.</li>
<li>If you dont want to physically modify your board, then there is 2 other solutions you could use instead. You can buy a data-only usb cable, but they will probably be expensive and difficult to find.</li>
<li>Modify your usb cable. It has 4 pins used by the board, +5v, GND, and the 2 data comms pins. All you have to do here is cut out or block the +5v. The GND pin is still needed as the data pins still draw power off the board.</li>
<li><strong>The arduino boards auto select a power source(the usb usually) if you have both usb and external power connected at the same time. A way to force the board into switching to the external power source instead, while supplying power to the data lines on the usb is to make sure the dc supply is greater than 6.6v.</strong> </li>
</ul>
<p><strong>Edit: That last one is for the 5v arduino boards, I just remebered the due works on 3.3v instead so this probably won't work on your board</strong></p>
|
13576 | |simulator|photoresistor| | How to change LDR output in simulator 123D Circuits? | 2015-07-19T19:51:56.407 | <p>I used simulator <a href="http://123d.circuits.io" rel="nofollow">123d.circuits.io</a> to create simulation of basic circuit with LDR: LDR is connected to 5V and via 10K resistor to GND. Wire between LDR and resistor is connected to analog pin where I read ADC values and display them using serial monitor. This works fine. But I would like to <em>how to change lighting level of LDR in simulation</em> because this way LDR shows still the same value. I tried putting LED or light bulb near LDR but it doesn't seem to have any influence. Any ideas?</p>
| <p>Ok, so I found it myself. You can click on LDR during simulation and bar to adjust lighting appears above it.</p>
|
13588 | |pins|arduino-due| | Read OUTPUT pin value in Arduino Due | 2015-07-20T12:02:48.573 | <p>I am trying to read the value of an output pin. online forums say that <code>digitalRead(pinNum);</code> should work, but that is not the case here. digitalRead always returns 0 (LOW).
This is the code:</p>
<pre><code>int pin = 22; // or 13, or 3 ...
void setup()
{
Serial.begin(9600);
pinMode(pin,OUTPUT);
}
void loop()
{
digitalWrite(pin,HIGH);
delay(100);
Serial.println(digitalRead(pin));
delay(100);
digitalWrite(pin,LOW);
delay(100);
Serial.println(digitalRead(pin));
delay(100);
}
</code></pre>
<p>printed values:</p>
<pre><code>0
0
0
...
</code></pre>
| <p>try editing...</p>
<pre><code>Serial.println(digitalRead(pin));
</code></pre>
<p>to .....</p>
<pre><code>Serial.println(digitalRead(pin), DEC);
</code></pre>
<p>This works on my arduino Leonardo.</p>
|
13592 | |arduino-mega| | Arduino restarts problem | 2015-07-20T15:24:49.807 | <p>I want to assign <code>-1</code> to <code>count</code> variable again when <code>count == 16</code> but when I have assigned <code>-1</code> inside the <code>if</code> condition I have marked below in the code, the Arduino restarts.</p>
<p>Can anyone guess what is wrong here?</p>
<pre><code>#include <LiquidCrystal.h>
#include <avr/pgmspace.h>
#include <hid.h>
#include <hiduniversal.h>
#include <usbhub.h>
#include <Usb.h>
#include <usbhub.h>
#include <avr/pgmspace.h>
#include <hidboot.h>
#include <SPI.h>
#define DISPLAY_WIDTH 16
// initialize the LCD library with the numbers of the interface pins
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
USB Usb;
USBHub Hub(&Usb);
HIDUniversal Hid(&Usb);
HIDBoot<HID_PROTOCOL_KEYBOARD> Keyboard(&Usb);
int count = -1;
char drawNo[4];
int m = 0;
int turn;
class KbdRptParser : public KeyboardReportParser {
void PrintKey(uint8_t mod, uint8_t key);
protected:
virtual void OnKeyDown(uint8_t mod, uint8_t key);
virtual void OnKeyPressed(uint8_t key);
};
void KbdRptParser::OnKeyDown(uint8_t mod, uint8_t key) {
uint8_t c = OemToAscii(mod, key);
count++;
if (c)
{ OnKeyPressed(c); }
}
/* what to do when symbol arrives */
void KbdRptParser::OnKeyPressed(uint8_t key) {
static uint32_t next_time = 0; //watchdog
static uint8_t current_cursor = 0; //tracks current cursor position
if (millis() > next_time) {
lcd.clear();
current_cursor = 0;
delay(5); //LCD-specific
lcd.setCursor(0, 0);
}//if( millis() > next_time ...
next_time = millis() + 200; //reset watchdog
if (current_cursor++ == (DISPLAY_WIDTH + 1)) { //switch to second line if cursor outside the screen
lcd.setCursor(0, 1);
}
int keys = (int) key;
if (count == 4 | count == 5 | count == 6 | count == 7) {
turn++;
drawNo[m] = (char)keys;
//lcd.print(drawNo[m]);
Serial.print(drawNo[m]);
Serial.print(m);
++m;
}
if (count == 16) {
Serial.println("Counter equals 16 NOW");
printScreen();
delay(200);
count = -1; /* <<<<<<<<<<<<<<<<<<<<<<<<<<<<Here is the problem*/
for (int i = 0; i < sizeof(drawNo); i++) {
drawNo[i] = (char)0;
}
}
}
void printScreen() {
int j;
lcd.print(" DRAW NO : ");
for (j = 0; j < 4; j++) {
lcd.print(drawNo[j]);
}
}
KbdRptParser Prs;
void setup() {
Serial.begin(115200);
Serial.println("Start");
if (Usb.Init() == -1) {
Serial.println("OSC did not start.");
}
delay(200);
Hid.SetReportParser(0, (HIDReportParser *)&Prs);
// set up the LCD's number of columns and rows:
lcd.begin(DISPLAY_WIDTH, 2);
lcd.clear();
lcd.noAutoscroll();
lcd.print("Scan Your Code");
delay(200);
}
void loop() {
Usb.Task();
}
</code></pre>
| <pre><code>int m = 0;
...
drawNo[m] = (char)keys;
...
++m;
</code></pre>
<p>No other references to <em>m</em> in your code. Therefore <em>m</em> keeps increasing and you are writing outside the bounds of the array <em>drawNo</em>, corrupting memory.</p>
|
13594 | |i2c|c|avr| | Software I2C - ATmega8 | 2015-07-20T15:29:47.670 | <p>I am using ATmega8 with 12MHz crystal, on my breadboard. I can use <code>SDA</code> and <code>SCL</code> pins with default arduino library <code>wire.h</code>, and it works. But I want another pins to use I<sup>2</sup>C protocol.</p>
<p>I tried this <a href="http://playground.arduino.cc/Main/SoftwareI2CLibrary" rel="nofollow">library</a>, even on real <code>SDA</code> and <code>SCL</code> pins, but it doesn't work.</p>
<p>I have pull up resistors, I tried with 10k and 4.7k without any success. (But those resistors worked with hardware I<sup>2</sup>C | TWI)</p>
<p>What am I doing wrong? (All connections is fine, because hardware TWI works but software does not.) Thank you for your help.</p>
<p>(Fuses are ok, because the Atmega won't respond if I remove the crystal oscillator, the LED blinking duration is ok.)</p>
<p>What i want to run (that doesn't work):</p>
<pre><code>#define SDA_PORT PORTC
#define SDA_PIN 4
#define SCL_PORT PORTC
#define SCL_PIN 5
//#define I2C_TIMEOUT 100
#include <SoftI2CMaster.h>
uint8_t ADDR = 0x68;
void setup(void) {
Serial.begin(19200);
Serial.println("Initializing ...");
i2c_init();
if (!i2c_start(ADDR | I2C_WRITE)) Serial.println(F("Device does not respond"));
if (!i2c_write(0x00)) Serial.println(F("Cannot address reg 0"));
i2c_stop();
}
void loop (void) {
unsigned int low0, high0, low1, high1;
unsigned int chan0, chan1;
unsigned int lux;
int state1;
int state2;
delay(1000);
i2c_start(ADDR | I2C_WRITE);
i2c_write(0x00);
i2c_rep_start(ADDR | I2C_READ);
low0 = i2c_read(false);
high0 = i2c_read(false);
low1 = i2c_read(false);
high1 = i2c_read(true);
i2c_stop();
Serial.print(low0);
}
</code></pre>
<p>And the code with hardware TWI that works:</p>
<pre><code>#include "Wire.h"
#define DS3231_I2C_ADDRESS 0x68
// Convert normal decimal numbers to binary coded decimal
byte decToBcd(byte val)
{
return( (val/10*16) + (val%10) );
}
// Convert binary coded decimal to normal decimal numbers
byte bcdToDec(byte val)
{
return( (val/16*10) + (val%16) );
}
void setup()
{
Wire.begin();
Serial.begin(19200);
pinMode(13, OUTPUT);
pinMode(5, INPUT);
}
void readDS3231time(byte *second,
byte *minute,
byte *hour,
byte *dayOfWeek,
byte *dayOfMonth,
byte *month,
byte *year)
{
Wire.beginTransmission(DS3231_I2C_ADDRESS);
Wire.write(0); // set DS3231 register pointer to 00h
Wire.endTransmission();
Wire.requestFrom(DS3231_I2C_ADDRESS, 7);
// request seven bytes of data from DS3231 starting from register 00h
*second = bcdToDec(Wire.read() & 0x7f);
*minute = bcdToDec(Wire.read());
*hour = bcdToDec(Wire.read() & 0x3f);
*dayOfWeek = bcdToDec(Wire.read());
*dayOfMonth = bcdToDec(Wire.read());
*month = bcdToDec(Wire.read());
*year = bcdToDec(Wire.read());
}
</code></pre>
<p>Schematic is the same as: <a href="https://www.arduino.cc/en/main/standalone" rel="nofollow">https://www.arduino.cc/en/main/standalone</a>.</p>
<p>Except instead of 16MHz, I use a 12MHz and ch210x serial.</p>
<p>Arduino's bootloader works well, I compiled it from source.</p>
| <p>OK let me cry till morning...</p>
<p>i was having this issue during day, but the solution was sooo easy</p>
<p>i need to pay attention more ...</p>
<blockquote>
<p>i2c_start(addr | R/W-bit)
Initiates a transfer to the slave device with the (8-bit) I2C address addr. </p>
</blockquote>
<p>what i was trying is to push <strong>7 bit</strong> address.</p>
<p>i hope this might help some others.</p>
<p>Thank you for help.</p>
|
13603 | |arduino-yun|sd-card| | Perfect copy of Yun with Micro SD | 2015-07-21T04:17:09.610 | <p>My Yun has a micro SD card with shared file system using <a href="https://www.arduino.cc/en/Tutorial/ExpandingYunDiskSpace" rel="nofollow">ExpandingYunDiskSpace</a>.</p>
<p>I would like to copy my Yun/SD card data <strong>perfectly</strong> onto my backup Yun/SD card. Because I have made many changes to the filesystem, just re-running the whole process manually would take a long time.</p>
<p>What methods can I use to transfer my Yun's data onto my other Yun?</p>
<p>My other Yun is brand new (never plugged in), and I have a brand new SD card in there. If I can do a 'bit-perfect' transfer for Yun and Micro SD in one shot that would be ideal.</p>
| <p>Copying an SD card (cloning) is easy enough to do. On Windows you can use <a href="http://www.raspberry-projects.com/pi/pi-operating-systems/win32diskimager" rel="nofollow">Win32DiskImager</a>. On Linux and OS X you can either use <code>dd</code> from the command line:</p>
<pre><code>(read)
$ dd if=/dev/sdb of=MySD.img bs=32k
(write)
$ dd id=MySD.img of=/dev/sdb bs=32k
</code></pre>
<p>For OS X the device names will be different, also in Linux you need to check which /dev/sd?? it is.</p>
<p>Also in Linux and OS X there are GUI applications that can do it for you - the Disk Manager in OS X, and "Gnome Disks" in Linux.</p>
<p>That is only good for the actual SD card contents though. If you need to clone the actual Yún itself then it becomes more tricky.</p>
<p>Fortunately there are tools available to help you.</p>
<p>Details on how to create and restore a backup of an OpenWRT system (which is what the Yún is) can be found on the OpenWRT Wiki: <a href="http://wiki.openwrt.org/doc/howto/generic.backup" rel="nofollow">http://wiki.openwrt.org/doc/howto/generic.backup</a></p>
<p>Note that again it requires a Linux or OS X (preferably the former) system to do it since it relies on the standard Unix scripting tools and commands that are lacking on a Windows system.</p>
<p>You may be able to do all the above on a Windows system if you make it look like a Linux system by installing Cygwin.</p>
|
13609 | |arduino-ide| | Prevent hardware and library examples from showing in the Sketchbook menu | 2015-07-21T16:34:03.423 | <p>I have various subdirectories in <code>{SKETCHBOOK}/hardware/</code> and <code>{SKETCHBOOK}/libraries/</code> that contain an <code>examples/</code> subdirectory. These examples are showing up in <code>File</code> | <code>Sketchbook</code> | <code>hardware</code> and <code>File</code> | <code>Sketchbook</code> | <code>libraries</code>. Is there any way I can prevent them from showing up in that menu without moving them under the system-level Arduino directory?</p>
| <p>Looking at the <a href="https://github.com/arduino/Arduino/blob/2c05841588313918a3fcab7ecbc01023a8621f6f/app/src/processing/app/Base.java#L1618" rel="nofollow">code</a> it is scanning all folders and there is no option to change that behavior. Also looking at the code, it looks like it dumps them into a sub-menu, hiding them away a little further, if the folder is named anything except "examples", which could be an alternative option for you.</p>
<p>The final option would be to fork your own version and come up with some exclusion logic, maybe with some kind of ".ignore" kind of logic where you can specify folders to exclude form the menu.</p>
|
13610 | |c++| | About Making Library | 2015-07-21T18:25:23.663 | <p>There is a tutorial in the Arduino website on how to create a library. The tutorial gives the following codes for the header:</p>
<pre><code>class Morse
{
public:
Morse(int pin);
void dot();
void dash();
private:
int _pin;
};
</code></pre>
<p>My questions are:</p>
<ol>
<li>What is the purpose of this line: <code>Morse(int pin);</code></li>
<li>If any, what is the name of this line?</li>
</ol>
| <pre><code>Morse(int pin);
</code></pre>
<p>is the <strong>constructor</strong> for the class, <code>Morse</code>.</p>
<p>The name of this line, and all of the other lines between the curly braces<code>{</code> and <code>}</code> are <strong>declarations</strong> of the members of the class <code>Morse</code>.</p>
<p>So, the line </p>
<pre><code>Morse(int pin);
</code></pre>
<p>is the <em>declaration</em> of the <em>constructor</em>, to answer both of your questions in one line.</p>
<p>Constructors are required pieces of code for Object Oriented Programming. When the constructor is called, it creates an object which is an instance of the class <code>Morse</code>. In this constructor is where all of the initialisation of the oblject goes. In the case of <code>Morse</code> it just initialises pin, which is specified in the parameter <code>pin</code>, by setting it to be an <code>OUTPUT</code>.</p>
<p>It is declared here, as a "signpost" if you will, for other parts of the code to know that it exists and is available to be called.</p>
|
13627 | |arduino-mega|shields|ethernet|usb| | Issues with Stacking Ethernet shield and USB Host shield | 2015-07-22T13:19:11.187 | <p>I want to stack Ethernet shield and USB host together with my Arduino MEGA 2560.
Each of these shields works fine separately.
Is it necessary to contact bootloader pins with each shield and arduino board?
I have connected and tried, but the problem exists.</p>
<p>only one shield works fine at once.(always the sheild that directly connect to the Arduino board).
How do I resolve this problem ? I want to work all 2 shields at once.</p>
<p>these are the sheilds I have used.</p>
<ol>
<li><a href="http://shieldlist.org/circuitsathome/usbhost-v2" rel="nofollow noreferrer">Circuits At Home USB Host Shield v2.0</a></li>
<li><a href="http://shieldlist.org/arduino/ethernet-v5" rel="nofollow noreferrer">Ethernet Shield v5.0</a></li>
</ol>
<p>Thank you</p>
| <p>Also, I think that there is an hardware bug on the USB Master shield: IC3, the 3-state buffer which converts MISO to 5V, is always active... The enable pin of this 74LVC1G125 (pin 1) should be connected to the pin ss_3V3. Then you can stack this shield with another one.</p>
|
13632 | |arduino-uno|power|voltage-level|battery| | 5V+ Voltage to the arduino analog | 2015-07-22T14:28:39.207 | <p>If I connect a 12V / 12V+ battery to the arduino (uno) analog, will it be damaged ? What if I connect 230-240V to it ? Don't worry I haven't tried it yet. :D</p>
<p>Thanks in advance.</p>
| <p>For the 12 V battery, let's assume it might get up to 15 to 20 V when charging, so we need a voltage divider to divide that down.</p>
<p><a href="https://i.stack.imgur.com/BbuxF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BbuxF.png" alt="Voltage divider"></a></p>
<p>The zener diode is there to clamp the input to no more than 5.1 V in case of spikes or other damaging things on the input. </p>
<p>The voltage divider will divide down to 25% of the input, ie.</p>
<pre><code>output = R2 / (R1 + R2) = 10 / (30 + 10) = 0.25
</code></pre>
<p>So now if you measure 5 V on the analog input you know you have 20 V on the battery. Thus you can scale your calculations appropriately.</p>
<p>(A more common value would be a 33 k resistor, in which case redo the calculation and scale accordingly).</p>
<hr>
<p>For 240 V I strongly advise against trying something like that with bigger resistors. For one thing, 240 V RMS will have 240 * sqrt (2) = <strong>340 V</strong> peak to peak. And that is both negative and positive.</p>
<p>A suitable approach would be to run through a small transformer, which will reduce the voltage and also isolate you from (almost) certain death.</p>
<p>In addition to that you would need to rectify the resulting voltage (say, 12 V) so that you don't put negative voltages into your input pin. And on top of that filter it so smooth out the peaks and troughs. </p>
|
13639 | |led| | Powering 30+ LEDs and flickering one at random | 2015-07-22T20:19:50.100 | <p>I'd like to power 30+ LEDs, while having a single LED (at random) flicker every 10-15 seconds.</p>
<p>Is this possible to do using an Arduino? I totally new to this so please bear with me.</p>
<p>This is the type of flicker effect I'm hoping to achieve: <a href="https://www.youtube.com/watch?v=753-lkao8l0" rel="nofollow">https://www.youtube.com/watch?v=753-lkao8l0</a></p>
<p>Many thanks</p>
| <p>Here is an example of a project that simultaneously drives 40 individually controllable LEDs directly connected to an ATTINY...</p>
<p><a href="http://ognite.com" rel="nofollow">http://ognite.com</a></p>
<p>The same technique would also work directly connecting LEDs to the Arduino IO pins. </p>
|
13641 | |arduino-uno|power|sleep| | How to mimic soft-power button in inexpensive toys & flashlights? | 2015-07-22T20:49:16.603 | <p>My kids have a few odd inexpensive toys with a soft push-button that will turn on the toy, and subsequent pushes change the toy's mode of operation in some fashon. A flashlight comes to mind, where the button is pushed once and it turns on, push again and it blinks, and a 3rd time and the light turns off.</p>
<p>I've looked inside one of these flashlights, and there's a small blob covering some IC, what looks to be a diode, and the usual connections for the batteries and lights.</p>
<p>How do these circuits "work" without immediately draining the batteries? I'm looking to mimic this behaviour on a battery powered arduino Uno (or possibly Pro Mini).</p>
<p>What comes to mind is that the button is on an interrupt line, which wakes the system up from some sleep state.. when the button cycles around to an "off" state, the system goes back to sleep.</p>
| <p>I have made a circuit in the past that does more or less this:</p>
<p><a href="https://i.stack.imgur.com/tOB8A.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tOB8A.png" alt="Latch Circuit"></a></p>
<p>There are two switches in the diagram - the one on the top right turns the circuit on, and the one lower-middle turns it off. Once turned on, it will stay on until the bottom switch is pressed.</p>
<p>The two resistors bottom left, and the switch at the bottom, represent your Arduino.</p>
<p>Note that, this diagram is OUTSIDE the arduino - it provides power TO the Arduino (and any other components relating to your project). That is, the bottom of the 1MOhm resistor, and the bottom of the left transistor, connect to the power pin on the Arduino. Those two resistors don't literally, exist.</p>
<p>It works as follows: The transistors do pretty much all the work. Both transistors work as switches. At the start (as shown in the diagram), both transistors have the same voltage at the base, and the emitter (the top one +5v between top and center/left; the bottom one 0v between center/right and bottom). This turns both switches off, and preserves the status quo, and consuming nearly no power.</p>
<p>As soon as the switch at the top is closed, the base (center/right) of the lower transistor is pulled up to +5V, switches this transistor on, and power can flow from this collector to the emitter. This means power can flow through the TOP transistor from emitter (top) to base (center/left), switching on the TOP transistor. This allows power to flow from the emitter (top) to collector (bottom). This takes over from the pushbutton, keeping the bottom transistor on. This is the other stable state.</p>
<p>At this point, power goes to the Arduino (bottom two resistors, representing load, and bottom switch, which is one of the pins on the Arduino. This pin should be set to "high impedance" until the Arduino wants to switch itself off, then it should go low. </p>
<p>I built the top part of the circuit, with an LED for the bottom half (both switches were just wires), and it worked, but I'd have to consider what would happen if the arduino pin is high or low while the top button is being pressed.</p>
|
13646 | |arduino-uno|robotics| | How do I make/get a odometer for a lunch box sized robot? | 2015-07-23T01:21:00.280 | <p>Say I have given the robot a map of the place, it needs to navigate it. I need a odometer to keep track of its current position in the map. I need it to be precise up to a cm.</p>
<p>Can I simply use the motor's RPM and the diameter of the wheel to calculate how much distance the robot has travelled, or is there any catch?</p>
<p>I searched Google and could not find any odometer small enough for my robot. Most of them are for bicycles.</p>
| <p>I had the idea to use a computer mouse (optical) to do this - cheap, easily available. You would need two, if you want to be able to measure turning rate, one on the left and one on the right.</p>
<p>You don't even need the whole mouse - if you pull it apart you can ditch the case, the buttons, and about half the circuitry. You will need to do some hacking to figure out how it works, but I doubt you'll find a cheaper odometer that is anywhere near as accurate.</p>
<p>Note: I pulled one apart, then got distracted on another project, but I can't think of a reason why it wouldn't work.</p>
|
13653 | |arduino-mega|arduino-ide|esp8266|solar| | How much numerical precision can the ESP8266 achieve? | 2015-07-23T10:57:46.590 | <p>Background: I am trying to port <a href="http://cerebralmeltdown.com/Sun_Tracking_and_Heliostats/" rel="nofollow">this solar tracker code</a> by Gabriel Miller to run on the ESP8266. Now I'm not a particularly great coder, but I'd like to give it an honest try.</p>
<p>As of recently, the ESP8266 can be natively programmed <a href="https://github.com/esp8266/Arduino" rel="nofollow">using the Arduino IDE and code base</a>. Which is pretty convenient.</p>
<p>SO. The solar tracker code written by Gabriel works on the Arduino Uno and the Arduino Mega. The Mega version of the code has a high-precision calculation library called 'BigNumber' to calculate the Sun's position in the sky to a pretty precise degree. My question is:</p>
<p>From what I've read, the ESP8266 is supposed to be a 32-bit microprocessor, so (I assume?) it should be able to handle high-precision numbers without using the BigNumber library; so, how do I check what's the highest numerical precision that the ESP8266 can support? That way I could theoretically just copy the equations over to the ported program rather than having to rewrite the BigNumber library.</p>
| <p>I ported the BigNumber library to the Arduino in 2012. The BigNumber library is based almost entirely on the GNU "bc" library. What it does is store numbers with arbitrary precision (ie. as large as you like, and with as many decimal places as you like).</p>
<p>For example, on the Uno you can calculate 3<sup>160</sup> like this:</p>
<pre><code>3^160 = 21847450052839212624230656502990235142567050104912751880812823948662932355201
</code></pre>
<p>Or, the square root of 2 to 100 decimal places:</p>
<pre><code>sqrt(2) = 1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727
</code></pre>
<p>It's up to you how many decimal places you want. However the trade-off is RAM and speed. The more precision, the more RAM and the slower it is.</p>
<p>A normal precision float (like on the Uno/Mega) has around 7 decimal digits of precision. A <em>double</em> float has around 16 decimal digits of precision. See <a href="https://en.wikipedia.org/wiki/Floating_point" rel="nofollow">Wikipedia - Floating point</a>.</p>
<p>If the ESP8266 has a C++ compiler then you could probably convert the BigNumber library without too many issues. However if it supports double-precision floats you may not need to.</p>
<blockquote>
<p>How do I check what's the highest numerical precision that the ESP8266 can support?</p>
</blockquote>
<p>You may want to ask on the <a href="http://www.esp8266.com/" rel="nofollow">ESP8266 Community Forum</a> - they may be able to give you a more helpful answer.</p>
<hr>
<h3>Reference</h3>
<ul>
<li><a href="http://www.gammon.com.au/forum/?id=11519" rel="nofollow">Arbitrary precision (big number) library port for Arduino</a></li>
<li><a href="https://github.com/nickgammon/BigNumber" rel="nofollow">Source on Github</a></li>
</ul>
|
13658 | |arduino-due|keyboard| | How to send keyboard signals to two separate computers (arduino due) | 2015-07-23T21:38:52.747 | <p>The arduino due has 2 micro-usb ports that you can connect to two separate computers. I need to send different keyboard signals to each computer. How would I do this?</p>
| <p>While the Arduino Due has two separate USB ports, only one of them is a native port accessible to the processor. The second port is only usable for programming, and is connected to a different and much smaller chip that handles the programming task.</p>
<p>To connect to multiple computers from an Arduino Due, you have two options:</p>
<ul>
<li>You can <a href="https://arduino.stackexchange.com/questions/991/can-the-2nd-mcu-on-the-uno-r3-be-used-for-keyboard-emulation">reprogram the second MCU</a> to allow it to connect to the computer as a keyboard. This method is tricky because it requires an external programmer for it to work.</li>
<li>You can use a software USB implementation such as <a href="https://www.obdev.at/products/vusb/index.html" rel="nofollow noreferrer">V-USB</a> to use regular digital pins to connect to the computer. This is also tricky because it requires a little electronic know how a few extra components to make this work.</li>
</ul>
<p>Both options require a little something else to make it work, so you will have to pick based on what you feel more comfortable doing.</p>
|
13683 | |shields|gsm|communication| | Is the SIM900 3G? Or is the SIM900A able to connect to 3G? | 2015-07-24T23:26:49.180 | <p>I would like to state that I am not familiar with the whole cellular connection thing. But I was wondering if the SIM900/or/SIM900A is 3G and will work with <a href="http://www.ptel.com" rel="nofollow noreferrer">PTel Mobile</a>.</p>
<p>I need this Arduino to be able to travel and needs to connect to every PTel's tower. Will I be able to connect to 3G or only the 2G and the 1G networks?</p>
| <p>It will not be able to connect to a 3G or 4G network. There has to be a 2G network / support and that support is getting less.</p>
|
13688 | |power|motor| | reversing a micro motor by reversing two pins - one Source and one sink? | 2015-07-25T09:03:22.523 | <p>can I use this configuration of two pins to run a micro motor ,so I be able to change the polarity of the current (by the code itself-one time out pin1-high out pin2 - low , while next time one low two high!) every time I would like ?(and by changing the polarity OF THE CURRENT to the motor it will revers it) ! </p>
<p>Thank's !</p>
| <pre><code>**Required:**
Drive micro-motor directly from two processor pins.
- Pin 1 high / Pin 2 low for one direction.
- Pin 1 low / Pin 2 high for other direction.**
</code></pre>
<p>This is not a very good idea if it can be avoided but yes, you can operate a motor that way, providing that the motor current is low enough to meet the pin current ratings. It would have to be a very small motor to achieve this.</p>
<p>Take careful note of the current versus voltage drive capabilities of the processor concerned. While a pin may be shown as being able to source or sing 5 or 10 or 20 mA, this is accompanied by a voltage rise for a sink and voltage drop for a source, so at higher currents lower voltages will be available. </p>
<p>A danger is that motor noise may affect the processor.<br>
Placing a small capacitor across the motor will help, and driving the motor through a small resistor from each pin will also help keep noise away from the processor. But depending on the motor used this may not be enough.<br>
The series resistors will drop some voltage and so are limited in maximum allowable size.<br>
The parallel capacitor will slow the direction transition - the larger the capacitor the slower the change.</p>
<p>Using drivers or "buffers" which are higher current rated would allow a larger motor to be driven and would help isolate the processor from the motor noise. </p>
<p>Ask further if any idea here sounds useful.</p>
<hr>
<p>Added: Had a discussion with Gerben (below).<br>
I'd avoided mentioning "catch diodes" but this is an add on that can help.<br>
From each pin add a small Schottky diode* from pin to Vcc and pin to ground so that all 4 diodes are reverse biased.<br>
(ie Cathode goes to Vcc = line on diode on upper diodes.<br>
Anode goes to ground on "lower" diodes. )<br>
These diodes are usually non conducting. If motor operation or switching causes spikes that rise above Vcc or below ground these diodes will conduct (slightly) before the internal protection diodes do. This is not ideal but can help.<br>
As Gerben notes, when reversing the motor, driving BOTH pins to ground until the motor has stopped and then applying reversing polarity can help. Also driving both high will do the same. There are pros and cons with either method. </p>
<ul>
<li>eg <a href="http://www.diodes.com/datasheets/ds11005.pdf" rel="nofollow"><strong>BAT54</strong> surface mount</a>, <a href="http://www.st.com/web/en/resource/technical/document/datasheet/CD00000768.pdf" rel="nofollow"><strong>BAT48 through hole</strong></a>, <a href="http://www.digikey.com/product-search/en?k=schottky+diode+1n581&mnonly=0&newproducts=0&ColumnSort=1000011&page=1&stock=0&pbfree=0&rohs=0&quantity=1&ptm=0&fid=0&pageSize=25" rel="nofollow">1N581x</a> or similar.</li>
</ul>
|
13704 | |motor|pwm| | Can PWM break a DC motor? | 2015-07-25T20:37:45.863 | <p>I want to know if controlling the speed of a DC motor with PWM could break (burn out the DC motor. Sorry my English isn't that good.</p>
| <p>Providing that you send the appropriate voltage this shouldn't break your motor. The creator of Arduino suggest this way of driving motor on his book.
Source: Massimo Banzi's book : "getting started with arduino" : chapter 5 Advanced Input and Output.</p>
|
13709 | |arduino-uno|programming|motor|servo| | Servo motors won't work with motor controller | 2015-07-26T03:34:22.510 | <p>I have a motor controller controlling two motors, which works perfectly fine when I comment out the two servos in the below code. These two servos are not connected to the motor controller but simply being operated using other Arduino Uno pins, as seen in the code. </p>
<p>When the servo <code>attach()</code> functions are included in the code the motor controller only works with one of the motors and the other completely stops working. </p>
<p>I don't understand why the servos are interfering with the motor controller. What's going on here? </p>
<pre><code>#include <Servo.h>
Servo myServo1;
Servo myServo2;
int m1_ALI = 10;
int m1_BLI = 9;
int m2_ALI = 3;
int m2_BLI = 11;
int m1_AHI = 12;
int m1_BHI = 4;
int m2_AHI = 6;
int m2_BHI = 5;
void setup() {
//myServo1.attach(7);
//myServo2.attach(8);
pinMode(m1_AHI, OUTPUT);
pinMode(m1_ALI, OUTPUT);
pinMode(m1_BLI, OUTPUT);
pinMode(m1_BHI, OUTPUT);
pinMode(m2_AHI, OUTPUT);
pinMode(m2_ALI, OUTPUT);
pinMode(m2_BLI, OUTPUT);
pinMode(m2_BHI, OUTPUT);
}
void loop() {
moveForward(30);
}//end loop
void moveForward(int x){
digitalWrite(m1_AHI, LOW);
digitalWrite(m1_BLI, LOW);
digitalWrite(m1_BHI, HIGH);
digitalWrite(m2_AHI, LOW);
digitalWrite(m2_BLI, LOW);
digitalWrite(m2_BHI, HIGH);
analogWrite(m2_ALI, x);
analogWrite(m1_ALI, x);
}//end moveForward
</code></pre>
| <p>See Servo.cpp: </p>
<blockquote>
<p>Note that analogWrite of PWM on pins associated with the timer are disabled when the first servo is attached.
Timers are seized as needed in groups of 12 servos - 24 servos use two timers, 48 servos will use four.</p>
</blockquote>
<p>Also <a href="https://www.arduino.cc/en/Reference/Servo" rel="nofollow">Servo Library reference</a></p>
<blockquote>
<p>On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins. </p>
</blockquote>
<p>You are using pins 9 and 10 for your motors.</p>
<hr>
<p>analogWrite uses PWM, the servo library uses PWM, you have a conflict of resources here.</p>
|
13715 | |arduino-uno|c++| | How to Publish to MQTT with retain option | 2015-07-26T08:45:00.113 | <p>I don't understand how to publish to mqtt with retain option (The fourth parameters)</p>
<p>I know that I need length in an byte array but I've try allot to determine how to calculate my payload message to an byte var.</p>
<p>here is my code to publish once I am connected.</p>
<pre><code>String str;
char chBright[4];
str = String(ledBrightness); //converting integer into a string
str = str + '%';
str.toCharArray(chBright, 4);
MQTTClient.publish("/maison/GF/Escalier/stairLight/b", chBright);
</code></pre>
<p>document ask the third parameter to be an byte</p>
<blockquote>
<p>topic – the topic to publish to <code>char*</code></p>
<p>payload – the message to publish <code>byte array</code></p>
<p>length – the length of the message <code>byte</code></p>
<p>retained – whether the message should be retained <code>byte</code></p>
<blockquote>
<p><code>0</code> – not retained</p>
<p><code>1</code> – retained</p>
</blockquote>
</blockquote>
<p><a href="http://knolleary.net/arduino-client-for-mqtt/api/#publish3" rel="nofollow" title="Arduino client for mQTT info doc">mqtt client for Arduino</a></p>
<p><strong>How in c++ to get bytes from the message I want to publish?</strong></p>
<p>Tank you to clarify my knowledge</p>
| <blockquote>
<p>How to Publish to MQTT with retain option?</p>
</blockquote>
<p>The quick answer is add payload length, and retained as true as the last parameters to publish(). </p>
<pre><code>const int BUF_MAX = 8;
char buf[BUF_MAX];
itoa(ledBrightness, buf, 10);
strcat(buf, "%");
int len = strlen(buf) + 1;
MQTTClient.publish("/maison/GF/Escalier/stairLight/b", buf, len, true);
</code></pre>
<p>Above is a rewrite with the extra parameter for "retained", payload length, and payload as a null-terminated string. </p>
<p>Cheers!</p>
|
13718 | |power|battery|temperature-sensor|wireless| | Remote temperature and humidity sensor with long battery life | 2015-07-26T12:48:30.730 | <p>I want to build a remote sensor which will measure temperature (range 5-30°C) and humidity (range 20-90%) and provide regularly (in the range of one measurement every minute or tenth of minutes) the measurement via wireless. This sensor will be used indoor, mostly in dark areas.</p>
<p><em>Note: measurement could be done every minutes and sending them could be done immediately or in batch of 10 measurements or more).</em></p>
<p>I was looking to build this solution using an Arduino, DHT22 sensor and a radio transmitter using ZigBee or Z-Wave protocol, and power it via AA rechargeable batteries. But after studying this solution, I found that it would be challenging to even get <strong>a week of battery life</strong>, this would require using the radio sparingly and to try to use as much as possible the power modes of the Arduino ATmel controller.</p>
<p>That's <strong>not enough</strong>, I want a battery life in the range of several months, 1 month would be "acceptable", <strong>6 months would be the target</strong>, breakthrough would be > 1 year.</p>
<p><em>Note: I don't want wifi, this seems to suck even more power than the other mentioned radio protocol</em></p>
<h1>Questions</h1>
<p>Is there another more power efficient way to wireless-ly transmit the data?</p>
<p>Or shall I reconsider Arduino all together and look for another more power efficient controller?</p>
<p>Or is there another way?</p>
| <p>There is an excellent article on power reduction at <a href="http://www.gammon.com.au/power" rel="nofollow">http://www.gammon.com.au/power</a> , but it's definitely worth looking at the parts of your project OTHER than the arduino - that is, your sensor, and your radio. These tend to use much more than your Arduino.</p>
<p>There is some persistent storage on the Arduino - EEPROM - write all your data to that as you read it, then send it all in bulk. Most of the time your radio will spend will be start/end communication.</p>
<p>Making your board is not as daunting as it seems. Use a breadboard to develop & test your project, then use stripboard (aka veroboard) to build your project. You can cut the tracks with a sharp utility knife, or with a specialized stripboard cutting tool (accurate & easier than a knife).</p>
<p>If you are still nervous, find your local makerspace or hackerspace - there are people there that would be happy to teach you to solder, and help you work out your ideas.</p>
|
13720 | |sensors|spi|teensy| | Teensy: SPI and Pressure Sensor | 2015-07-26T14:19:01.460 | <p>I'm first time working with a Teensy 3.1. I have to connect this (MS5803-01BA: <a href="http://www.amsys.de/products/ms5803.htm" rel="nofollow">http://www.amsys.de/products/ms5803.htm</a>) pressure sensor via SPI to my Teensy.</p>
<p>My problem is, that I don't have any reliable knowledge on SPI. I read the Wikipedia for it and also the Teensy-Manual.</p>
<p>For the pressure sensor I already got a C-Code but it is only working with the ATMEL ATmega644p microcontroller. I tried to get the code to work with my Teensy, but it seems like I don't get either any input nor any output.</p>
<p>I hope that one of you can help me with the following code and tell me what I'm missing out on. Thank you.</p>
<p>Code:</p>
<p><a href="http://pastebin.com/xaWXfRUR" rel="nofollow">http://pastebin.com/xaWXfRUR</a></p>
<p>Datasheet of the pressure sensor:</p>
<p><a href="http://www.amsys.de/sheets/amsys.de.ms5803_01b.pdf" rel="nofollow">http://www.amsys.de/sheets/amsys.de.ms5803_01b.pdf</a></p>
<p>C-Code for the pressure sensor for the ATMEL ATmega644p microcontroller:
<a href="http://www.amsys.de/sheets/amsys.de.an520_e.pdf" rel="nofollow">http://www.amsys.de/sheets/amsys.de.an520_e.pdf</a></p>
<hr>
<p>PS: Please excuse my not perfect English for it's not my native language.</p>
| <p>Details about SPI at <a href="http://www.gammon.com.au/spi" rel="nofollow">SPI - Serial Peripheral Interface - for Arduino</a></p>
<p>This isn't right:</p>
<pre><code> SPI.transfer(CMD_ADC_READ); // send ADC read command
SPDR = SPI.transfer(0x00); // send 0 to read 1st byte (MSB)
ret = SPDR;
temp = 65536 * ret;
SPDR = SPI.transfer(0x00); // send 0 to read 2nd byte
ret = SPDR;
temp = temp + 256 * ret;
SPDR = SPI.transfer(0x00); // send 0 to read 3rd byte (LSB)
</code></pre>
<p>The SPI library handles SPDR for you. Writing to it yourself will corrupt its behaviour.</p>
<p>It should be more like:</p>
<pre><code> SPI.transfer(CMD_ADC_READ); // send ADC read command
ret = SPI.transfer(0x00); // send 0 to read 1st byte (MSB)
temp = 65536 * ret;
ret = SPI.transfer(0x00); // send 0 to read 2nd byte
temp = temp + 256 * ret;
ret = SPI.transfer(0x00); // send 0 to read 3rd byte (LSB)
</code></pre>
<p>Ditto for elsewhere.</p>
|
13732 | |arduino-uno|motor| | that no matter what the inputs are Motor1 always moves | 2015-07-27T10:31:50.467 | <pre><code>int motor_forward1 = 7;
int motor_reverse1 = 6;
int motor_forward2 = 5;
int motor_reverse2 = 4;
int motor_forward3 = 3;
int motor_reverse3 = 2;
int sensor1 = A0;
int sensor2 = A1;
void setup()
{
pinMode(motor_forward1, OUTPUT);
pinMode(motor_reverse1, OUTPUT);
pinMode(motor_forward2, OUTPUT);
pinMode(motor_reverse2, OUTPUT);
pinMode(motor_forward3, OUTPUT);
pinMode(motor_reverse3, OUTPUT);
pinMode(sensor1, INPUT);
pinMode(sensor2, INPUT);
}
void loop()
{
if (digitalRead(A0) == HIGH)
{
digitalWrite(motor_forward1,1);
digitalWrite(motor_reverse1,0);
delay(5000);
digitalWrite(motor_forward1,0);
digitalWrite(motor_reverse1,1);
delay(5000);
digitalWrite(motor_forward1,0);
digitalWrite(motor_reverse1,0);
delay(1000);
}
else if (digitalRead(A1) == HIGH)
{
digitalWrite(motor_forward2,1);
digitalWrite(motor_reverse2,0);
delay(5000);
digitalWrite(motor_forward2,0);
digitalWrite(motor_reverse2,1);
delay(5000);
digitalWrite(motor_forward2,0);
digitalWrite(motor_reverse2,0);
delay(1000);
}
else
{
digitalWrite(motor_forward3,1);
digitalWrite(motor_reverse3,0);
delay(5000);
digitalWrite(motor_forward3,0);
digitalWrite(motor_reverse3,1);
delay(5000);
digitalWrite(motor_forward3,0);
digitalWrite(motor_reverse3,0);
delay(1000);
}
delay(5000);
}
</code></pre>
<p>Schematic <a href="https://i.stack.imgur.com/Fz92a.png" rel="nofollow noreferrer"><strong>here</strong></a>.</p>
| <p>The code isn't wrong, it's far too simple to be at fault.</p>
<p>The error is from within Proteus. Those 'pushbutton' switches (and the other switch simulations) are not quite as straightforward as one would like. They have an OFF resistance, usually 100 Megaohms, but that's enough to trick the simulation into not behaving like it should do. You MUST pull the inputs to ground with a resistor - any sensible value will do as it's only required for the <em>simulation</em>. As they are, they're in some odd floating/magic/unknown state; common sense does not apply here!</p>
<p>An alternative is to swap the pushbutton for a SPDT switch; connect the common to the Arduino and the other contacts to the 7805 output and ground. You won't need the resistor in this case.</p>
|
13736 | |arduino-mega|c++|lcd|sd-card| | Printing SD card file contents on LCD | 2015-07-27T18:37:22.640 |
<p>This is a part of my program which reads data from file stored in SD card and displays that on an LCD screen.</p>
<pre class="lang-C++ prettyprint-override"><code> File dataFile = SD.open("1165.txt");
if (dataFile) {
Serial.println("File Opened");
lcd.clear();
delay( 5 ); //LCD-specific M
lcd.setCursor( 0,0 );
while (dataFile.available()) {
Serial.write(dataFile.read());
lcd.write(dataFile.read());
lcd.print(dataFile.read());
}
dataFile.close();
} else {
// if the file didn't open, print an error:
Serial.println("error");
}
</code></pre>
<p>When I look at the serial monitor it prints the contents of that file but none of these commands print what is printed in the serial monitor,</p>
<pre class="lang-C++ prettyprint-override"><code>lcd.write(dataFile.read());
lcd.print(dataFile.read());
</code></pre>
<p>Any ideas?</p>
| <p>You could also implement a readLine routine, similar to:</p>
<pre><code>void _readLine(File f, char *line)
{
boolean cr_found = false;
int p = 0;
while (f.available()) {
char b = f.read();
if(b!='\r' && b!='\n')
line[p++] = b;
if(b == '\r') cr_found = true;
if((b == '\n') && cr_found) break;
}
line[p] = '\0';
}
</code></pre>
<p>And read the SD file line by line, processing each one of them by its own.</p>
<pre><code>char buffer[32];
while(dataFile.available()) {
_readLine(dataFile, buffer);
// do something with buffer
}
</code></pre>
|
13760 | |arduino-uno|c++|nrf24l01+| | nRF24L01 module using Mirf library was working and then stopped | 2015-07-28T14:45:36.860 |
<p>I have two nRF24L01 modules, they are both attached to a sensor shield that has special ports for this type of module, on Arduino Unos.</p>
<p><a href="https://i.stack.imgur.com/aungh.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aungh.jpg" alt="Sensor shield, with nRF24LO1 in it"></a></p>
<p>I have this code on the Arduino that is sending the signal:</p>
<pre class="lang-C++ prettyprint-override"><code>#include <MirfHardwareSpiDriver.h>
#include <MirfSpiDriver.h>
#include <Mirf.h>
#include <nRF24L01.h>
#include <SPI.h>
#include <Wire.h>
//0 = stop, 1 = left, 2 = right, 3 = forward, 4 = backwards
long command;
long last_command;
long Joystick_1_X;
long Joystick_1_Y;
long Joystick_1;
void setup() {
// put your setup code here, to run once:
Mirf.spi = &MirfHardwareSpi;
Mirf.init();
Mirf.setTADDR((byte *)"serv1");
Mirf.payload = sizeof(long);
Mirf.config();
Serial.begin(115200);
}
void loop() {
Joystick_1_X = analogRead(A0);
Joystick_1_Y = analogRead(A1);
if(Joystick_1_X < 450){
command = 1;
}else if(Joystick_1_X > 600){
command = 2;
}else if(Joystick_1_Y > 600){
command = 3;
}else if(Joystick_1_Y < 400){
command = 4;
}else{
command = 0;
}
if(command == last_command){
}else{
Mirf.send((byte *)&command);
last_command = command;
}
}
</code></pre>
<p>and this code on the Arduino that is receiving </p>
<pre class="lang-C++ prettyprint-override"><code>#include "SPI.h"
#include "Mirf.h"
#include "nRF24L01.h"
#include "MirfHardwareSpiDriver.h"
int TN1= 3;
int TN2 = 4;
int ENA = 9;
int TN4 = 5;
int TN3 = 6;
int ENB = 10;
long data;
void setup() {
pinMode(TN1, OUTPUT);
pinMode(TN2, OUTPUT);
pinMode(TN3, OUTPUT);
pinMode(TN4, OUTPUT);
pinMode(ENA, OUTPUT);
pinMode(ENB, OUTPUT);
Mirf.spi = &MirfHardwareSpi;
Mirf.init();
Mirf.setRADDR((byte *)"serv1");
Mirf.payload = sizeof(long);
Mirf.config();
Serial.begin(115200);
Serial.print("begin");
}
void loop() {
// put your main code here, to run repeatedly:
receiveCommand();
if(data == 1){
left();
}else if(data == 2){
right();
}else if(data == 3){
forward();
}else if(data == 4){
backwards();
}else if(data == 0){
stop_rover();
}
}
void receiveCommand(){
if(!Mirf.isSending() && Mirf.dataReady()){
Mirf.getData((byte *)&data);
Mirf.rxFifoEmpty();
Serial.print(data);
}else{
Serial.println("No data to be recieved");
}
}
void forward(){
digitalWrite(ENB, HIGH);
digitalWrite(ENA, HIGH);
digitalWrite(TN4, HIGH);
digitalWrite(TN3, LOW);
digitalWrite(TN1, HIGH);
digitalWrite(TN2, LOW);
}
void backwards(){
digitalWrite(ENB, HIGH);
digitalWrite(ENA, HIGH);
digitalWrite(TN4, LOW);
digitalWrite(TN3, HIGH);
digitalWrite(TN1, LOW);
digitalWrite(TN2, HIGH);
}
void left(){
digitalWrite(ENA, HIGH);
digitalWrite(TN1, HIGH);
digitalWrite(TN2, LOW);
}
void right(){
digitalWrite(ENB, HIGH);
digitalWrite(TN4, HIGH);
digitalWrite(TN3, LOW);
}
void stop_rover(){
digitalWrite(ENB, LOW);
digitalWrite(ENA, LOW);
digitalWrite(TN4, LOW);
digitalWrite(TN3, LOW);
digitalWrite(TN1, LOW);
digitalWrite(TN2, LOW);
}
</code></pre>
<p>This was working, and the rover did spin its wheels when the remote broadcasted a signal, but then it just stopped. The sensor shield says that they are plugged into the 3V port, I tried using the RF24 library and that did not work either.</p>
<p>Any help would be greatly appreciated.</p>
| <p>Using the MIRF Library that I got from <a href="http://www.sainsmart.com/zen/documents/20-011-401/Codes_for_Self-balancing_robot.zip" rel="nofollow">here</a>, and then using this code to send </p>
<pre><code> Mirf.send((byte *)&command);
while(Mirf.isSending()){
}
</code></pre>
<p>and this code to receive</p>
<pre><code> if(!Mirf.isSending() && Mirf.dataReady()){
Mirf.getData((byte *)&data);
Mirf.rxFifoEmpty();
else(){
}
</code></pre>
<p>I was able to get it to work</p>
|
13763 | |arduino-mega|i2c|library|data-type|byte-order| | Using union to return a range of bits from a data frame: wrong approach? | 2015-07-28T19:24:33.827 | <p>I'm working on an adaptation of Jason Leyrer's <a href="http://www.jleyrer.net/blog/2008/03/wii-guitarduino/" rel="nofollow noreferrer">Guitar Hero Library</a> for Arduino. My version is for a DJ Hero controller, and I've also borrowed some code from this Arduino forum thread: topic=120527 (sorry can't post links yet).</p>
<p>The protocol is i2c and I am successfully reading data from it, however I'm not 100% sure what to do with the data.</p>
<p>The buttons are fine, as they are mapped to just one bit in a given byte. However the other controls are a combination of 4, 5 and 6 bit longs.</p>
<p>The format according to Wiibrew is like so:</p>
<p><a href="https://i.stack.imgur.com/RVhDH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RVhDH.png" alt="Table of DJ Hero dataframe format"></a></p>
<ul>
<li><code>BE</code> is for Euphoria button</li>
<li><code>CS</code> : Crossfade Slider, lower is left and upper is right</li>
<li><code>SX</code> and <code>SY</code> are the black analog stick.</li>
<li><code>ED</code> is the Effect Dial</li>
<li><code>RTT</code> is the turntable on the right as a 6-bit signed integer (positive = CW; negative = CCW)</li>
<li><code>RBG</code>,<code>RBR</code>,<code>RBB</code> are the Green, Red and Blue buttons on the right</li>
<li>LTT is the turntable on the left as a 6-bit signed integer (positive = CW; negative = CCW)</li>
<li><code>LBG</code>,<code>LBR</code>,<code>LBB</code> are the Green, Red and Blue buttons on the left</li>
</ul>
<p>I'm trying to do this:</p>
<pre class="lang-c prettyprint-override"><code> signed long DJ_ED()
{
pack5 ED;
ED[0] = (DJ_buf[3] >> 5) & 1;
ED[1] = (DJ_buf[3] >> 6) & 1;
ED[2] = (DJ_buf[3] >> 7) & 1;
ED[3] = (DJ_buf[2] >> 5) & 1;
ED[4] = (DJ_buf[2] >> 6) & 1;
return ED;
}
</code></pre>
<p>Where pack5 is the following:</p>
<pre class="lang-c prettyprint-override"><code>#define packet5
union pack5
{
signed long value;
int ints[5];
};
</code></pre>
<p>but I'm getting the following error:</p>
<p><code>no match for 'operator[]' (operand types are 'pack5' and 'int')</code></p>
<p>What am I doing wrong?</p>
|
<p>You are using a union so you have to specify which part of the union you want. Your function should read:</p>
<pre class="lang-C++ prettyprint-override"><code> signed long DJ_ED()
{
pack5 ED;
ED.ints[0] = (DJ_buf[3] >> 5) & 1;
ED.ints[1] = (DJ_buf[3] >> 6) & 1;
ED.ints[2] = (DJ_buf[3] >> 7) & 1;
ED.ints[3] = (DJ_buf[2] >> 5) & 1;
ED.ints[4] = (DJ_buf[2] >> 6) & 1;
return ED.value;
}
</code></pre>
<p>It still looks wrong because you are only putting a single bit into those 5 bytes (because of the & 1). And 5 x int will be a lot longer than one signed long.</p>
<hr>
<p>The code below seems to match the data structure you posted an image of:</p>
<pre class="lang-C++ prettyprint-override"><code>struct packedFields
{
// byte 0
unsigned int sx : 5;
unsigned int rtt_4_3 : 3;
// byte 1
unsigned int sy : 5;
unsigned int rtt_2_1 : 3;
// byte 2
unsigned int rtt_5 : 1;
unsigned int cs : 4;
unsigned int ed_4_3 : 2;
unsigned int rtt_0 : 1;
// byte 3
unsigned int ltt_4_0 : 5;
unsigned int ed : 3;
// byte 4
unsigned int ltt_5 : 1;
unsigned int rbr : 1;
unsigned int b_plus : 1;
unsigned int filler_2 : 1;
unsigned int b_minus : 1;
unsigned int lbr : 1;
unsigned int filler_1 : 2;
// byte 5
unsigned int filler_4 : 2;
unsigned int rbb : 1;
unsigned int lbg : 1;
unsigned int be : 1;
unsigned int rbg : 1;
unsigned int filler_3 : 1;
unsigned int lbb : 1;
};
union packedFieldsUnion
{
packedFields a;
byte b [6];
};
void doSomethingWithTheFields (packedFieldsUnion & theFields); // prototype
void doSomethingWithTheFields (packedFieldsUnion & theFields)
{
theFields.a.rtt_4_3 = 3;
theFields.a.ltt_4_0 = 2;
} // end of doSomethingWithTheFields
void setup ()
{
Serial.begin (115200);
Serial.println ();
Serial.print (F("packedFields sized = "));
Serial.println (sizeof (packedFields));
packedFieldsUnion foo;
memset (&foo, 0, sizeof foo);
doSomethingWithTheFields (foo);
Serial.println (F("-- packedFields bytes --"));
for (int i = 0; i < sizeof foo; i++)
Serial.println ((int) foo.b [i], HEX);
} // end of setup
void loop ()
{
} // end of loop
</code></pre>
<p>I have a bitwise struct, as Ignacio Vazquez-Abrams suggested. Testing indicates you put the low-order bits first. Then I made a union of this struct and 6 bytes. You can't fit the whole thing into a signed long anyway (a long is 4 bytes) so that part of your code was doomed to fail.</p>
<p>A small bit of test code proves that the bits are being accessed in the correct way. You still need to fiddle around with things like RTT which has individual bits scattered in different places.</p>
<hr>
<p>If you look at the data format you posted there are 6 bytes, not 5. They are numbered 0, 1, 2, 3, 4, 5. A total of six of them.</p>
|
13764 | |hardware|wires|multiplexer| | Good tips for how to connect cables into Mux Shield II? | 2015-07-28T08:35:54.760 | <p>I just got a Mux Shield 2 and got it working as I expected. Now I started to find out how to actually connect the I/O cables to the board. Doesn't seem to be as simple as I thought. I don't want to solder cables into the board for maintenance reasons. So, does anyone have any good tips on how to do this?</p>
<p><a href="https://i.stack.imgur.com/tHo9p.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tHo9p.jpg" alt="Photo of shield"></a></p>
| <p>Solder 100-mil male headers onto the board, then use 100-mil crimp terminals to connect the wires.</p>
<p><a href="https://i.stack.imgur.com/edU2P.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/edU2P.jpg" alt="100-mil male headers"></a>
<a href="https://i.stack.imgur.com/DRMxf.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DRMxf.jpg" alt="Female crimp terminals"></a>
<a href="https://i.stack.imgur.com/L50td.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L50td.jpg" alt="Connected"></a></p>
|
13771 | |mpu6050| | I2Cdev #include weirdness | 2015-07-29T06:08:58.253 | <p>I am using <a href="https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/MPU6050" rel="nofollow">Jeff Rowberg's MPU6050 library</a>, and I simply don't understand what is going on in the following lines of the first example (MPU6050_raw.ino):</p>
<pre><code>#include "I2Cdev.h"
#include "MPU6050.h"
// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE
// implementation is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include <Wire.h>
#endif
</code></pre>
<p>So, what I got from that is, if I2Cdev is using Wire instead of some alternative I2C library, I should include Wire.h. I really don't see why that's necessary, so I removed the line in which Wire.h is included, and got this error:</p>
<pre><code>C:\Users\Franco2500k\Documents\Arduino\libraries\I2Cdev/I2Cdev.h:80:26: fatal error: Wire.h: No such file or directory
#include <Wire.h>
</code></pre>
<p>So, apparently, I2Cdev.h already tries to include Wire.h, but somehow fails? And another #include a few lines later goes back in time and fixes everything? Can someone explain what is going on?</p>
| <p>The Arduino IDE means well, really it does. It copies your source, the device core, and any libraries used by your source all to a separate directory so that it doesn't poison any of their original locations unintentionally.</p>
<p>But of course, there's something missing from that list. The IDE <em>doesn't copy libraries used by other libraries</em>. Therefore if you don't include Wire.h in your .ino file then Wire will be missing from the build and you get the error observed. Cracktastic.</p>
|
13773 | |wires|prototype|multiplexer| | How can I turn this into an (Ableton) controller? | 2015-07-29T06:30:51.407 | <p>I found this lovely decade box in a demolished house recently and want to turn it into an Ableton controller. As you see, there are 18 knobs, each with 12 individual states. </p>
<p>I'd like to have a program which can access the states of all the knobs at any time, and I have an arduino which I can use. Is this possible to do without a shield?</p>
<p>My first thought is that, since many of the leads on the back already have resistors on them, I could use a sort of total-resistance-across-the-connection approach which would suit itself to the analog inputs. But I'm not sure that's the way to go, especially if I want very low latency.</p>
<p>How can I wire up a board that has digital access to all the pins here? How does a multiplexer play into this? How many inputs would I need? I am super new to this kind of stuff, so I imagine this must be a pretty simple answer.</p>
<p>Thanks for your help.</p>
<p><a href="https://i.stack.imgur.com/fUlgW.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fUlgW.jpg" alt="enter image description here"></a><a href="https://i.stack.imgur.com/64SC2.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/64SC2.jpg" alt="enter image description here"></a></p>
| <p>The other answers are excellent, however I want to address this question:</p>
<blockquote>
<p>How does a multiplexer play into this? </p>
</blockquote>
<p>Just as an example of how multiplexing helps, I opened up a <a href="http://www.gammon.com.au/forum/?id=12298" rel="nofollow noreferrer">scrolling LED sign</a> which has 504 individual LEDs which "appear" to be all on at once (if wanted).</p>
<p>Internally were 10 x <a href="http://www.gammon.com.au/forum/?id=11518" rel="nofollow noreferrer">74HC595</a> serial shift registers. 9 of them were hooked up to the individual columns (giving 72 columns), and the last one was connected to the 7 rows. </p>
<pre><code> 9 * 8 = 72 columns
72 * 7 = 504 LEDs
</code></pre>
<p>Thus we could turn on 504 LEDs. However to have individual LEDs appear to come on the code has to turn on one row (out of the 7) and then output the pattern for that row to the 72 columns. Then it switches to another row, does the next pattern, and so on.</p>
<p>I have a <a href="https://vimeo.com/80312101" rel="nofollow noreferrer">video of this effect</a> on Vimeo.</p>
<p>If you do it fast enough, all the LEDs appear to be one at once.</p>
<hr>
<p>Now you can do this for switches too, just connect all the individual positions together, and then apply "power" to each switch in sequence, and read the results. This time you want an <strong>input</strong> shift register, eg. the <a href="http://www.gammon.com.au/forum/?id=11979" rel="nofollow noreferrer">74HC165</a> for the reading, and an output register for powering each switch.</p>
<p>The problem is with switches though, that you would get "phantom" reads because switches aren't diodes (or, worse, the inactive switches would short the power to ground). So you would need a <strong>diode</strong> in series with each switch to prevent that. Ah well, diodes are cheap.</p>
<p>This is exactly the same concept as the way keypads work. Say, a 16-key keypad will have 8 wires: 4 rows and 4 columns.</p>
<hr>
<p>Having said all that, you will still need quite a few chips unless you set up quite a complex "simulated" keypad array. Maybe it wouldn't be too bad. </p>
<p>You have 17 switches so that would be 2 x 74HC595 for activating each switch, plus one spare pin on the Arduino. And the switches seem to have around 12 positions, so that would be 2 x 74HC165 to read which position it was at.</p>
<p>So, for each switch, you make that one HIGH and the others LOW. Current will flow through the diodes and the rotary switch, presenting a HIGH on one of the 12 "reading" pins. The diodes stop the current from shorting the HIGH to the LOW through other switches.</p>
<p>You take a reading, and move onto the next switch. This can be done quickly, in the same way the LED sign scrolls so fast you can't spot any flickering.</p>
<p>This schematic illustrates the idea:</p>
<p><a href="https://i.stack.imgur.com/na69k.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/na69k.png" alt="Rotary switch example"></a></p>
<p>In this example we apply a HIGH to the common part (rotor) of the left switch. It goes through the diode, and the selected position, to make input "read 1" high. The diode on the other switch prevents the HIGH from being shorted to the LOW, even though both switches are in the same position.</p>
<p>You would need a pull-down resistor for each of the 12 "reading" lines, so that if they weren't being forced HIGH, they would read LOW. And one diode per rotary switch. So, not too many extra parts. And the wiring is simple, just connect each corresponding switch pin together (except for the common one, of course).</p>
<p>I think this will work, unless anyone can see a major flaw. :)</p>
|
13795 | |power|arduino-micro|multiplexer| | Arduino + 4051 -> noise on certain 4051 pins | 2015-07-30T00:47:01.337 |
<p>I am trying to use two <code>4051</code> ICs with an Arduino Micro right now. The idea was to have an 16-sensor demo station (8 sensors per <code>4051</code>) wherein each <code>4051</code> pin selection is controlled by a potentiometer as input. I am new to using MUX's, so I mocked the following up as a quick demo based on <a href="http://playground.arduino.cc/Learning/4051" rel="nofollow">this</a> help document via Arduino (it's basically the same), which only uses one <code>4051</code> and does not use a potentiometer as selector input. So, I should be able to set the variable <code>which</code> to whatever number (0 - 7) to change the sensor selection that shows up at <code>A2</code> on the Arduino.</p>
<p>Setting <code>which</code> to 0 is fine, but when I have more than two sensors plugged into <code>4051</code> and set the selector pin to any other number than 0 there is a strong likelihood that the output that shows up in the <code>Serial Monitor</code> is both unresponsive to the selected sensor change and appears to be simply noise (random numbers around 200 or so). I have been trying to isolate where this noise is coming from and am totally stumped. Has anyone had this issue and, if so, any suggestions on how to further diagnose what is happening? I am currently powering everything off of the Arduino <code>5V</code>, which I am under the impression should be okay, though I have tried this with external power supplies (<code>12V at 2A</code>, for example) and gotten the same results (so I am fairly certain power is not the issue here).</p>
<p>Measuring voltage on pins 2, 3, and 4, I am seeing 1mV on pin 2, 1mV on pin 3, and 0.9mV on pin 4 following the initial spike during upload. When comparing against the Arduino 4051 doc I linked to above, I see that in that file pins 2, 3, and 4 show a Voltage of 2.5V following the initial spike during upload. Any idea what I am doing incorrectly?</p>
<pre class="lang-C++ prettyprint-override"><code>/*
Sensor Station via MUX
* code example for useing a 4051 * analog multiplexer / demultiplexer
* by david c. and tomek n.* for k3 / malm� h�gskola
*
* edited by Ross R.
*/
int r0 = 0; //value of select pin at the 4051 (s0)
int r1 = 0; //value of select pin at the 4051 (s1)
int r2 = 0; //value of select pin at the 4051 (s2)
int which = 0; //which y pin we are selecting
int val;
void setup() {
pinMode(A2, INPUT); // mux1 input
pinMode(2, OUTPUT); // s0
pinMode(3, OUTPUT); // s1
pinMode(4, OUTPUT); // s2
}
void loop () {
which = (0);
// select the bit
r0 = bitRead(which, 0);
r1 = bitRead(which, 1);
r2 = bitRead(which, 2); // use this with arduino 0013 (and newer versions)
digitalWrite(2, r0);
digitalWrite(3, r1);
digitalWrite(4, r2);
//Either read or write the multiplexed pin here
// refactor, this should be digitalWrite with millis or something
val = analogRead(A2); // MUX ouputs here
Serial.print("sensor number ");
Serial.print(which);
Serial.print('\t');
Serial.print("val is ");
Serial.println(val);
delay(2);
}
</code></pre>
| <p>I have a post about that chip at <a href="http://www.gammon.com.au/forum/?id=11976" rel="nofollow noreferrer">74HC4051 multiplexer / demultiplexer</a>.</p>
<p>I made up the circuit shown on my page above with modifications as described below:</p>
<p><a href="https://i.stack.imgur.com/QD3j2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QD3j2.png" alt="74HC4051 example"></a></p>
<p>I moved the A/B/C and O/I pins to match your code.</p>
<p>A is the <strong>low-order bit</strong> so pin 11 on the 74HC4051 should go to D2 on the Arduino.</p>
<pre><code>74HC4051 Arduino Meaning
11 D2 A
10 D3 B
9 D4 C
3 A2 O/I
</code></pre>
<p>I put a pot on I/O0 (pin 13 on the 74HC4051) and randomly set the other pins to +5 V or Gnd, as shown.</p>
<hr>
<p>In <code>setup()</code> I added:</p>
<pre class="lang-C++ prettyprint-override"><code>Serial.begin (115200);
</code></pre>
<p>I also modified it to automatically sequence through all 8 possible ports, and then stop after 1000 iterations to stop flooding the USB port on my computer. Code is:</p>
<pre class="lang-C++ prettyprint-override"><code>int r0 = 0; //value of select pin at the 4051 (s0)
int r1 = 0; //value of select pin at the 4051 (s1)
int r2 = 0; //value of select pin at the 4051 (s2)
int which = 0; //which y pin we are selecting
int val;
void setup() {
Serial.begin (115200);
pinMode(A2, INPUT); // mux1 input
pinMode(2, OUTPUT); // s0
pinMode(3, OUTPUT); // s1
pinMode(4, OUTPUT); // s2
} // end of setup
unsigned long counter;
void loop () {
// select the bit
r0 = bitRead(which, 0);
r1 = bitRead(which, 1);
r2 = bitRead(which, 2); // use this with arduino 0013 (and newer versions)
digitalWrite(2, r0);
digitalWrite(3, r1);
digitalWrite(4, r2);
//Either read or write the multiplexed pin here
// refactor, this should be digitalWrite with millis or something
val = analogRead(A2); // MUX ouputs here
Serial.print("sensor number ");
Serial.print(which);
Serial.print('\t');
Serial.print("val is ");
Serial.println(val);
delay(2);
if (++which > 7)
which = 0;
if (++counter >= 1000)
{
Serial.flush ();
exit (1);
}
} // end of loop
</code></pre>
<hr>
<p>The output from your sketch was as expected:</p>
<pre class="lang-none prettyprint-override"><code>sensor number 0 val is 781
sensor number 1 val is 0
sensor number 2 val is 1023
sensor number 3 val is 1023
sensor number 4 val is 0
sensor number 5 val is 0
sensor number 6 val is 0
sensor number 7 val is 1023
</code></pre>
<p>I suggest you check that your wiring agrees with mine.</p>
|
13798 | |arduino-uno| | Strange comportment of stepper motor while connected to internet | 2015-07-30T04:27:18.363 | <p>Problem moving a stepper motor after reading a value from a webpage....</p>
<p>I have a project to move a stepper motor from an angle after reading a number from internet; I have a typical 28BYJ-48 stepper with the hardware driver and an arduino + ethernet shield.</p>
<p>I have tested the motor alone with different library and it is working very well, the motor turn correctly to the proper angle and without shaking.</p>
<p>I have also been able to read a specific page with a number on it with the Ethernet shield and library. I am able to light a led whenever a certain value is read from this webpage.</p>
<p>Once I connect the 2 parts, either the stepper motot is vibrating a lot and moving from half the correct angle, either it is only shaking and not moving at all....</p>
<p>Note: I have powered it with an external power source thinking it was because of power issues but it doesn't change anything.....</p>
<p>I don't get it... Why would it work well before the etheret connection an not after?? Maybe it's late and I miss something obvious, but frankly I spent a lot of time looking online and checking my code</p>
<p>Here is my sketch if it anyone could help... thanks a lot in advance, I know it's quite long....but i'm quite desperate :-(</p>
<pre><code>#include <AccelStepper.h>
#include <Ethernet.h>
#include <SPI.h>
////////////////////////////////////////////////////////////////////////
//CONFIGURE
////////////////////////////////////////////////////////////////////////
#define HALFSTEP 8
// Motor pin definitions
#define motorPin1 8 // IN1 on the ULN2003 driver 1
#define motorPin2 9 // IN2 on the ULN2003 driver 1
#define motorPin3 10 // IN3 on the ULN2003 driver 1
#define motorPin4 11 // IN4 on the ULN2003 driver 1
// Initialize with pin sequence IN1-IN3-IN2-IN4 for using the AccelStepper with 28BYJ-48
AccelStepper stepper1(HALFSTEP, motorPin1, motorPin3, motorPin2, motorPin4);
const int stepsPerRev = 2038;
byte server[] = { 192,168,0,11 }; //ip Address of the server you will connect to
String serverIP = "192.168.0.11";
int port = 8888; // server port
// if need to change the MAC address (Very Rare)
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// byte ip[] = { 192, 168, 0, 188 }; // case we want to use fixed IP
//The location to go to on the server
//make sure to keep HTTP/1.0 at the end, this is telling it what type of file it is
String webPage = "/index.php HTTP/1.0";
EthernetClient client;
char inString[32]; // string for incoming serial data
int stringPos = 0; // string index counter
boolean startRead = false; // is reading?
int ledPin = 5;
String pageValue;
//////////////////////////////////////////////////////////////////////////////
// SETUP
//////////////////////////////////////////////////////////////////////////////
// setup the stepper parameters
void setup() {
stepper1.setMaxSpeed(3000.0);
stepper1.setAcceleration(1000.0);
stepper1.setSpeed(500);
// start a full rotation ==> this is perfectly working!!
int steps = degreesToSteps(360);
stepper1.moveTo(steps);
stepper1.runToPosition();
Serial.begin(9600);
Serial.println("starting communication");
//Connect the Ethernet Shield by specifying the board's mac and ip address
if(Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
}else{
Serial.println("Ethernet shield connected & obtained IP address : ");
Serial.println(Ethernet.localIP());
//Shield already connected during setup phase, now connect to the webpage and retrieve the value
//Connect to the server
if(!connectToServer(server, port, webPage)){
Serial.println("Failed to connect to server");
}else{
Serial.println("connected to server page");
//Read the output value written on the webpage
int angle = readPage().toInt();
Serial.println(angle);
int steps = degreesToSteps(angle);
Serial.println(steps);
stepper1.moveTo(steps);
stepper1.runToPosition();
delay(1000);
//end of success case connection
}
}
//end of setup
}
void loop(){}
///////////////////////////////////////////////////////////////////////////////////////////
//Connect to a web page
////////////////////////////////////////////////////////////////////////////////////////////
boolean connectToServer(byte* server, int port, String webPage)
{
//connect to the server
Serial.println("connecting...");
//port 8888 for our mamp server
if (client.connect(server, port)) {
Serial.println("connected");
client.print("GET ");
client.println(webPage);
client.println();
return true;
}else{
Serial.println("connection failed");
return false;
}
}
///////////////////////////////////////////////////////////////////////////////////////////
//Parse a value located between a < and a >
////////////////////////////////////////////////////////////////////////////////////////////
String readPage(){
//read the page, and capture & return everything between '<' and '>'
stringPos = 0;
memset( &inString, 0, 32 ); //clear inString memory
while(true){
if (client.available()) {
char c = client.read();
if (c == '<' ) { //'<' is our begining character
startRead = true; //Ready to start reading the part
}else if(startRead){
if(c != '>'){ //'>' is our ending character
inString[stringPos] = c;
stringPos ++;
}else{
//got what we need here! We can disconnect now
startRead = false;
client.stop();
client.flush();
Serial.println("disconnecting.");
return inString;
}
}
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////
//Convert the degrees into the closest number of steps relative to the step motor model.
////////////////////////////////////////////////////////////////////////////////////////////
int degreesToSteps(float angleDegrees) {
//return the closest number of steps to accomplish to move the motor for the specified angle
const float stepsPerDegree = stepsPerRev/360.00;
int steps = angleDegrees * stepsPerDegree + 0.5; // we add 0.5 as when converting to an int the floating part is truncated, this allows to round the value to the nearest Int
return steps;
}
</code></pre>
| <p>Pin 11 is used for SPI to communicate with the Ethernet Shield. And pin 10 is used for the ChipSelect.
So using the ethernet shield will toggle those pins, making the motor shake around.</p>
<p>Try using pins 6, 7, 8, and 9 instead.</p>
|
13808 | |arduino-uno|programming|gsm|debugging| | Why I could not read the other sms's except the first SMS? | 2015-07-30T12:23:14.317 | <p>I have to read the incoming SMS on my GSM module SIM900, and I want to print the sender number and message to the serial monitor.</p>
<p>I first configure the GSM module with AT commands and Response() function will give me the response to AT commands.</p>
<p>as any SMS will be in the following pattern</p>
<p>+CMT: "[Mobile number]", "[Date and Time]>"
[message body]</p>
<p>So, I first extract +CMT and after that I will take mobile number and at last we have message body. The code I have used is</p>
<pre><code>char RcvdMsg[200] = "";
int RcvdCheck = 0;
int RcvdConf = 0;
int index = 0;
int RcvdEnd = 0;
char MsgMob[15];
char MsgTxt[50];
int MsgLength = 0;
void Config() // This function is configuring our SIM900 module i.e. sending the initial AT commands
{
delay(1000);
Serial.print("ATE0\r");
Response();
Serial.print("AT\r");
Response();
Serial.print("AT+CMGF=1\r");
Response();
Serial.print("AT+CNMI=1,2,0,0,0\r");
Response();
}
void setup()
{
Serial.begin(9600);
Config();
}
void loop()
{
RecSMS();
}
void Response() // Get the Response of each AT Command
{
int count = 0;
Serial.println();
while(1)
{
if(Serial.available())
{
char data =Serial.read();
if(data == 'K')
{
Serial.println("OK");
break;
}
if(data == 'R')
{
Serial.println("GSM Not Working");
break;
}
}
count++;
delay(10);
if(count == 1000)
{
Serial.println("GSM not Found");
break;
}
}
}
void RecSMS() // Receiving the SMS and extracting the Sender Mobile number & Message Text
{
if(Serial.available())
{
char data = Serial.read();
if(data == '+'){RcvdCheck = 1;}
if((data == 'C') && (RcvdCheck == 1)) {RcvdCheck = 2;}
if((data == 'M') && (RcvdCheck == 2)) {RcvdCheck = 3;}
if((data == 'T') && (RcvdCheck == 3)) {RcvdCheck = 4;}
if(RcvdCheck == 4)
{
RcvdConf = 1;
RcvdCheck = 0;
}
if(RcvdConf == 1)
{
if(data == '\n'){RcvdEnd++;}
if(RcvdEnd == 3){RcvdEnd = 0;}
RcvdMsg[index] = data;
index++;
if(RcvdEnd == 2){RcvdConf = 0;MsgLength = index-2;index = 0;}
if(RcvdConf == 0)
{
Serial.print("Mobile Number is: ");
for(int x = 4;x < 17;x++)
{
MsgMob[x-4] = RcvdMsg[x];
Serial.print(MsgMob[x-4]);
}
Serial.println();
Serial.print("Message Text: ");
for(int x = 46; x < MsgLength; x++)
{
MsgTxt[x-46] = RcvdMsg[x];
Serial.print(MsgTxt[x-46]);
}
Serial.println();
Serial.flush();
}
}
}
}
</code></pre>
<p>The problem of the code is</p>
<p>After receiving first SMS I am getting my mobile number and message body. After that I am only getting the sender number printed to my serial monitor but not the message body.</p>
<p>Where has it gone wrong. I could not understood.</p>
<p>Please help me.......Thanks in advance.</p>
| <pre><code> {
MsgTxt[x-46] = RcvdMsg[x];
Serial.print(MsgTxt[x-46]);
}
RcvdEnd =0;
Serial.println();
Serial.flush();
</code></pre>
|
13816 | |library| | Updating MAX7456 library to work with Arduino 1.6.6 | 2015-07-30T21:39:27.383 | <p>I've got <a href="https://www.dropbox.com/s/3cp4am1f271odcm/max7456.tar?dl=0" rel="nofollow">this library</a> for communicating with the <a href="https://www.sparkfun.com/datasheets/BreakoutBoards/MAX7456.pdf" rel="nofollow">MAX7456 chip</a>.</p>
<p>The library is abandoned and the only one I found that actually works, so I'd really like to use it.</p>
<hr>
<p>It compiles fine with Arduino IDE 1.0.5, but not with Arduino IDE 1.6.6 .</p>
<p>This happens with 1.6.6, I tried to fix it but I only made it worse.</p>
<pre><code>Arduino: 1.6.6 Hourly Build 2015/07/03 10:26 (Linux), Board: "Arduino Nano, ATmega328"
Using library SPI at version 1.0.0 in folder: /home/t/Dropbox/Arduino-IDE/hardware/arduino/avr/libraries/SPI
Using library max7456 in folder: /home/t/Dropbox/Arduino/libraries/max7456 (legacy)
/home/t/Dropbox/Arduino-IDE/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10606 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR -I/home/t/Dropbox/Arduino-IDE/hardware/arduino/avr/cores/arduino -I/home/t/Dropbox/Arduino-IDE/hardware/arduino/avr/variants/eightanaloginputs -I/home/t/Dropbox/Arduino-IDE/hardware/arduino/avr/libraries/SPI -I/home/t/Dropbox/Arduino/libraries/max7456 /tmp/build4912026784583215357.tmp/sketch/HelloWorld.cpp -o /tmp/build4912026784583215357.tmp/sketch/HelloWorld.cpp.o
In file included from HelloWorld.ino:2:0:
/home/t/Dropbox/Arduino/libraries/max7456/max7456.h:228:40: error: 'prog_uchar' does not name a type
static void getCARACFromProgMem(const prog_uchar *table, byte i,charact c);
^
/home/t/Dropbox/Arduino/libraries/max7456/max7456.h:228:52: error: ISO C++ forbids declaration of 'table' with no type [-fpermissive]
static void getCARACFromProgMem(const prog_uchar *table, byte i,charact c);
^
Error compiling.
</code></pre>
<hr>
<p>How would one make the library compatible with 1.6.6?</p>
|
<p>In the file max7456.h at line 228 change it from:</p>
<pre class="lang-C++ prettyprint-override"><code>static void getCARACFromProgMem(const prog_uchar *table, byte i,charact c);
</code></pre>
<p>to:</p>
<pre class="lang-C++ prettyprint-override"><code>static void getCARACFromProgMem(const char *table, byte i,charact c);
</code></pre>
<hr>
<p>In the file max7456.cpp at line 484 change it from:</p>
<pre class="lang-C++ prettyprint-override"><code>void Max7456::getCARACFromProgMem(const prog_uchar *table, byte i, charact car)
</code></pre>
<p>to:</p>
<pre class="lang-C++ prettyprint-override"><code>void Max7456::getCARACFromProgMem(const char *table, byte i, charact car)
</code></pre>
<hr>
<p>Then it compiles OK (under 1.6.4 at least).</p>
|
13818 | |bluetooth| | Can I use a 6 pin Bluetooth module in a 4 pin socket? | 2015-07-30T23:41:49.640 | <p>I have a Funduino joystick shield and it features a 4 pin bluetooth socket in the top right hand corner (just above the <code>D</code>, <code>T</code>, <code>-</code> and <code>+</code> legends).</p>
<p><a href="https://i.stack.imgur.com/WTA15.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WTA15.jpg" alt="Joystick Shield"></a></p>
<p>For some reason, on eBay, 6 pin bluetooth modules are cheaper and more common than 4 pin bluetooth modules. </p>
<p><a href="https://i.stack.imgur.com/rjTEf.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rjTEf.jpg" alt="Bluetooth Module"></a></p>
<p>The joystick shield's 4 pin socket is labelled <code>R T - +</code>. Obviously these correspond with <code>RXD</code>, <code>TXD</code>, <code>GND</code> and <code>VCC</code> on the bluetooth module. </p>
<p>I was wondering:</p>
<ol>
<li>What is the difference between the 4 pin and 6 pin modules?</li>
<li>Can I use a 6 pin module in the four pin socket on the joystick shield?</li>
<li>What is the function of additional <code>STATE</code> and <code>EN</code> pins on the bluetooth module?</li>
<li>Are these two additional pins necessary as other modules do not have them? </li>
</ol>
| <blockquote>
<ol>
<li>What is the difference between the 4 pin and 6 pin modules?</li>
</ol>
</blockquote>
<p>The 6-pin modules have more pins, used for other features.</p>
<blockquote>
<ol start="2">
<li>Can I use a 6 pin module in the four pin socket on the joystick shield?</li>
</ol>
</blockquote>
<p>I don't see why not, as long as you tie/float the other pins appropriately.</p>
<blockquote>
<ol start="3">
<li>What is the function of additional STATE and EN pins on the bluetooth module?</li>
</ol>
</blockquote>
<p>Whatever the documentation says they do.</p>
<blockquote>
<ol start="4">
<li>Are these two additional pins necessary as other modules do not have them?</li>
</ol>
</blockquote>
<p>Probably not. But they provide additional functionality.</p>
|
13822 | |arduino-uno| | Building a digital camera? | 2015-07-31T03:07:59.463 | <p>Does anyone know of a way to DIY a digital camera by buying a sensor and lens and processing the image using an Arduino?</p>
| <p>You can buy a camera module for the Arduino, and you can interface it fairly simply. There are numerous modules around - ask Google, it knows more than me.</p>
<p>But I have yet to work out why people do it. All you can do with an Uno is to pass the data through to something else like a PC to process the image - so why wouldn't you just use a simple webcam?</p>
<p>The Arduino UNO has 2KB of RAM. A 24-bit 640x480 image (VGA) requires (640*480*3)/1024 = 900KB to store it in memory. If you really wanted to process an image on an Uno then you would be limited to (say 8-bit grayscale) 48x32 pixels (1.5KB) which is pretty pointless really.</p>
<p>Even a Due would only allow (again grayscale) around 320x240 (which is better) but nothing colour unless you want to start messing with CLUTs which aren't fun when receiving a truecolour (24-bit) image from a camera.</p>
<p>For this kind of task you are better off with an embedded computer with plenty of RAM such as a Raspberry Pi or maybe a Galileo or something.</p>
|
13827 | |arduino-mega| | What are the connectors used in the arduino mega? | 2015-07-31T09:38:00.020 | <p>I am trying to build a shield for an arduino mega.For that i need to know the type of the female connectors that are soldered in the pins of the arduino mega in order to choose the correct male connectors.</p>
| <p>Look for male pin header strip, with 0.1 inch (2.54mm) pitch.</p>
<p>In single and dual row form.</p>
<p>Specifically they are:</p>
<ul>
<li>8x1 ADCL</li>
<li>8x1 ADCH</li>
<li>8x1 PWML </li>
<li>8x1 PWMH </li>
<li>8x1 Communication</li>
<li>6x1 Power</li>
<li>18x2 digital IO (on the side)</li>
</ul>
<p>Source: <a href="https://www.arduino.cc/en/uploads/Main/arduino-mega-schematic.pdf" rel="nofollow">Schematics</a></p>
|
13835 | |sensors| | Use the TCS3200 color sensor without the included LEDs | 2015-07-31T18:13:10.073 | <p>just a quick question. I want to know if it is possible to use the TCS3200 color sensor without the 4 LEDs included on the breakout board. I want to get the sky colors. Is that possible?</p>
| <p>The photodiodes in the device itself have filters so it should <em>theoretically</em> be possible to use it without auxiliary light sources. Note, however, that the green and blue sensors have <em>two</em> sensitivity peaks and so using it outdoors without an infrared filter is not advised.</p>
|
13838 | |arduino-mega| | What are the distances between Arduino Mega connectors? | 2015-07-31T19:49:38.873 | <p>I am trying to build an Arduino Mega shield. For that, I need to know the exact distances between the different connectors.</p>
| <p>The pin layout and dimensions of the Mega are as follows:
<a href="https://i.stack.imgur.com/a1uUG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/a1uUG.png" alt="Mega Board layout."></a></p>
<p>Dimensions are in thousandths of an inch. <a href="https://blog.arduino.cc/2011/01/05/nice-drawings-of-the-arduino-uno-and-mega-2560/" rel="nofollow noreferrer">Source</a></p>
|
13839 | |arduino-uno|arduino-leonardo|analogread|adc|analogreadresolution| | Can I use analogReadResolution() on an Uno or Leonardo? | 2015-07-31T20:24:52.960 | <p>I am trying to get a spectrum analyser up and running. I found the following code on <a href="https://communities.intel.com/docs/DOC-23406" rel="nofollow">Galileo GEN2 Project - Real-Time Audio Spectrum Analyzer</a><sup>1</sup>:</p>
<pre><code>/*
*
* Galileo GEN2 Project - Real-Time Audio Spectrum Analyzer
* https://communities.intel.com/docs/DOC-23406
*
*
* ERROR: analogReadResolution() ???
*
*/
#include <stdint.h> //For New Arduino
#include "PCD8544.h"
#define pin_adc 0
#include "fix_fft.h"
char im[128];
char data[128];
int analog_value[128];
int i=0;
PCD8544 nokia = PCD8544(3, 4, 5, 7, 6);
// pin 7 - Serial clock out (SCLK) connects Dig3
// pin 6 - Serial data out (DIN) connects Dig4
// pin 5 - Data/Cmd. selct. (D/C) connects Dig5
// pin 4 - LCD reset (RST) connects Dig6
// pin 3 - LCD chip select (CS) connects Dig7
void setup() {
nokia.init();
nokia.command(PCD8544_DISPLAYCONTROL | PCD8544_DISPLAYNORMAL);
nokia.clear();
analogReadResolution(8);
}
void show_big_bars(char *spektrum) {
int spek_for_draw;
nokia.drawline(10, 15, 10, 39, BLACK);
for (byte i = 1; i < 64; i++){ // Skip 0 Channel
// Serial.print(spektrum[i],BYTE);
spek_for_draw = 1.5*(spektrum[i]); // 0/2.5 ~ 255/2.5
if (spek_for_draw > 39) spek_for_draw = 39;
nokia.drawline(i+10, 39 - spek_for_draw, i+10, 39, BLACK);
}
//nokia.drawstring(5, 5, "0 09 22 36 49");
nokia.drawstring(5, 5, "0");
nokia.drawstring(21, 5, "4");
nokia.drawstring(37, 5, "8");
nokia.drawstring(48, 5, "12");
nokia.drawstring(67, 5, "18");
nokia.drawstring(5, 0, "Spectrum");
nokia.drawstring(5, 1,"* 0.1KHz");
nokia.display(); // Update Screen
nokia.clear(); // Clear Screen for the animation
}
void loop(){
static long tt;
int val;
if (i < 128){
analog_value[i] = analogRead(pin_adc);
i++;
}
else{
for (i=0; i< 128;i++){ //Prepare data for FFT
data[i] = analog_value[i] - 128;
im[i] = 0;
}
//this could be done with the fix_fftr function without the im array.
fix_fft(data,im,7,0);
// I am only interessted in the absolute value of the transformation
for (i=0; i< 64;i++)
data[i] = sqrt(data[i] * data[i] + im[i] * im[i]);
//do something with the data values 1..64 and ignore im
show_big_bars(data);
i=0;
}
}
</code></pre>
<p>When I attempt to compile the above code, I get the error</p>
<pre><code>Arduino: 1.6.5 (Mac OS X), Board: "Arduino Micro"
fft_galileo.ino: In function 'void setup()':
fft_galileo:31: error: 'analogReadResolution' was not declared in this scope
'analogReadResolution' was not declared in this scope
</code></pre>
<p>When I search for the location of <code>analogReadResolution()</code> on Google, I repeatedly get the information that it is only available for the Due and Zero. From <a href="https://www.arduino.cc/en/Reference/AnalogReadResolution" rel="nofollow">Arduino - AnalogReadResolution</a>:</p>
<blockquote>
<p>analogReadResolution() is an extension of the Analog API for the
Arduino Due and Zero.</p>
</blockquote>
<p>I was wondering if I needed to add an <code>#include</code> statement but all of the code examples that I found do not have any specific <code>#include</code> for the Analogue library. </p>
<p>Also, thinking maybe it is board specific (as the video <a href="https://www.youtube.com/watch?v=C_cQ7vYTnWw" rel="nofollow">Arduino Due error: 'analogReadResolution' was not declared in this scope</a> suggests), I selected the <strong><em>Duemilanove</em></strong> board (as the <strong><em>Due</em></strong> is not on offer in my "Board" menu), but I still get the same error. I have even tried the <strong><em>Arduino NG or older</em></strong> Board menu item, but with the same results.</p>
<p>So, how do I get rid of this compile time error? Or, more poignantly, how can I compile this code for my Uno or Leonardo board. Should I just comment it out? If I do comment the line out then the code <em>does</em> compile, so does this mean that <code>analogReadResolution()</code> is not required any longer?</p>
<p>If it isn't required, then why does this Uno specific example, <a href="http://circuitdigest.com/microcontroller-projects/arduino-uno-adc-tutorial" rel="nofollow">How to Use ADC in Arduino Uno?</a>, state:</p>
<blockquote>
<p>As default we get the maximum board ADC resolution which is 10bits,
this resolution can be changed by using instruction
(“analogReadResolution(bits);”). This resolution change can come in
handy for some cases.</p>
</blockquote>
<p>How can the resolution be changed if the method has, indeed, been deprecated?</p>
<p>Also, why do I not have a "Due" in my <strong>Board</strong> menu?</p>
<hr>
<p><sup>1</sup> For completeness <code>fix_fft.h</code> and <code>fix_fft.cpp</code> can be found on <a href="https://github.com/TJC/arduino/tree/master/sketchbook/libraries/fix_fft" rel="nofollow">TJC's github</a> and here is the <a href="http://120.107.171.121/~tywua/sub/ISAR/Intel_Nokia5110.rar" rel="nofollow">PCD8544 Arduino library for Nokia 5510 LCD</a> library. The password for decompressing <code>Intel_Nokia5110.rar</code> file is 406. </p>
| <blockquote>
<p>Also, why do I not have a "Due" in my Board menu?</p>
</blockquote>
<p>See:</p>
<p><a href="https://i.stack.imgur.com/EeYBw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EeYBw.png" alt="Board manager menu item"></a></p>
<p>Then:</p>
<p><a href="https://i.stack.imgur.com/x4WJF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/x4WJF.png" alt="Board manager install"></a></p>
<hr>
<blockquote>
<p>I selected the Duemilanove board (as the Due is not on offer in my "Board" menu) ...</p>
</blockquote>
<p>The Duemilanove and the Due are completely different boards, with different processors.</p>
|
13851 | |c++|compile|memory-usage| | Why does this code execute? | 2015-08-01T05:48:18.827 | <p>After experiencing failures of my Arduino projects due to low memory, I decided to do some research into it so I could understand better where the problems were. I eventually came to this code:</p>
<pre><code>void setup() {
pinMode(13, OUTPUT);
int len = 5000;
byte *data = (byte *)malloc(len * sizeof(*data));
}
void loop() {
int timing = 1000;
delay(timing);
digitalWrite(13, HIGH);
delay(timing);
digitalWrite(13, LOW);
}
</code></pre>
<p>I expected that since my Arduino Uno does not have enough RAM to hold an array of 5000 bytes (<a href="http://www.atmel.com/devices/atmega328p.aspx?tab=parameters" rel="nofollow">Atmel's information</a> on the Atmega328P shows us it only has 2KB of SRAM), the code in <code>void loop()</code> would not be able to run due to lack of memory. As far as my understanding goes, once <code>malloc</code> has allocated 5000 bytes (or as many as it could of the 5000 bytes), there would physically not be enough space left in memory for the variable <code>timing</code> and the LED I attached on pin 13 would not flash on and off at intervals of 1 second.</p>
<p>However, my LED toggles at perfect intervals of 1 second. Why would this occur? Isn't memory allocated by <code>malloc</code> unavailable for use by anything else until <code>free</code> is called on it?</p>
| <p>If you add a debugging print you will see what is happening:</p>
<pre><code>void setup() {
Serial.begin (115200);
Serial.println ();
pinMode(13, OUTPUT);
int len = 5000;
byte *data = (byte *)malloc(len * sizeof(*data));
Serial.print ("data = ");
Serial.println ((int) data);
}
</code></pre>
<p>Output:</p>
<pre><code>data = 0
</code></pre>
<p>The malloc failed, it returned NULL, the rest of the program proceeded normally.</p>
<hr>
<blockquote>
<p>once malloc has allocated 5000 bytes (or as many as it could of the 5000 bytes)</p>
</blockquote>
<p><code>malloc</code> does not return with a partial allocation. It either allocates the amount you requested or none at all.</p>
|
13852 | |button| | Detect button on a ground line (reverse eng) | 2015-08-01T06:10:06.950 | <p>I've found a circuit board that has a couple of circuits (buttons, IR Receiver, LED, USB). The thing is that following the line for interfacing the buttons I came across what seems to be like buttons that are connected only to the ground line of the PCB while the other end is a free pin cable.</p>
<p>Is there a way for the arduino to detect the ground when the button is pressed or a way to detect a short of some kind? There is a smd and a resistor on both buttons. </p>
<p>Circuit:</p>
<p>Main Ground-----Button-----SMD Capacitor-----Resistor(101)-----Free Pin </p>
<p>Thanks in advance!</p>
<p>Edit: Circuit Board</p>
<p><a href="https://i.stack.imgur.com/6xpiZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6xpiZ.jpg" alt="Circuit Description"></a></p>
| <p>I did some research on the subjects and I came with a solution: <a href="http://blog.kennyrasschaert.be/blog/2014/04/01/digital-input-on-an-arduino-using-a-push-button/" rel="nofollow">I borrowed the code from here</a> and made some modifications to fit my needs. </p>
<pre><code>const int buttonPin = 6;
const int buttonPin1 = 7;
int previousReading = HIGH;
int previousReading1 = HIGH;
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(buttonPin1, INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
int reading = digitalRead(buttonPin);
int reading1 = digitalRead(buttonPin1);
if (previousReading == HIGH && reading == LOW) {
Serial.println(HIGH);
}
if (previousReading1 == HIGH && reading1 == LOW) {
Serial.println(LOW);
}
previousReading = reading;
previousReading1 = reading1;
}
</code></pre>
|
13858 | |sensors|i2c|pull-up| | Use TSL2561 and DS1307 RTC together | 2015-08-01T08:41:01.650 | <p>I want to use a TSL2561 light sensor and a DS1307 RTC and a couple of other sensors like DS18B20, AS3935, ML8511, MQ135, 433 mhz sender together with an Arduino.
However on Adafruit I read this today (Quote from Adafruit)</p>
<blockquote>
<p>You may be wondering, how is it OK to connect a 3.3V chip like the
TSL2561 to 5.0V data pins like the Arduino? Isn't that bad? Well, in
this specific case its OK. I2c uses pullup lines to the 3.3V power
pin, so the data is actually being sent at 3.3V. As long as all the
sensors/device on the i2c bus are running on 3.3V power, we're fine.
However, don't use a 5.0v powered i2c device (like the DS1307) with
pullups at the same time as a 3.3V device like the TSL2561! If you
want to use this sensor with a datalogger that uses the DS1307, remove
any/all of the pullup resistors from the DS1307 SDA/SCL pins. The
pullups built into the TSL2561 will then be active and keep the
voltage at 3.3V which is safe for both the RTC and the sensor.</p>
</blockquote>
<p>I don't really understand the meaning of this. What am I supposed to do? It tells me to remove the pullup lines on the RTC, but what are they and where can I find them? Are there any other sensors where I have to do this? If I don't remove the pullup lines, will I damage anything? Can someone clarify those things to me? </p>
| <p>You can use the DS1307 itself just fine, but you are probably using a breakout board. These boards have (pull-up) resistors on it that will pull-up the I2C lines to 5v, while you only want 3.3v. This will not damage the arduino, but could damage chips like the TSL2561, that can only handle 3.3v. </p>
<p><a href="https://i.stack.imgur.com/nXxvD.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nXxvD.jpg" alt="RTC breakout"></a></p>
<p>On the board you indicated you are using, you need to remove R2 and R3</p>
<p>Other 5v sensor breakout might also have pull-ups to 5v. Easiest way to check, is to connect 5v and ground, and then measure the voltage on the SDA and SCL pins. If it's 5v, then it has pull-up resistors that need to be removed.</p>
|
13862 | |rfid| | RDM630 RFID Reader on Beaglebone Black? | 2015-08-01T12:03:12.747 | <p>I have an RFID reader RDM-630 with these specifications: <a href="http://www.seeedstudio.com/depot/datasheet/RDM630-Spec..pdf" rel="nofollow">http://www.seeedstudio.com/depot/datasheet/RDM630-Spec..pdf</a></p>
<p>Could I connect this to a Beaglebone Black?</p>
| <p>Found what I was looking for and the answer is yes.</p>
|
13868 | |arduino-uno|led|pins|clones| | Sending "Blink" to pin 12 is causing on-board led to blink? | 2015-08-01T17:03:39.413 | <p>I recently picked up an <a href="http://www.avmicrotech.com/shop/product.php?id_product=123" rel="nofollow">Uno clone</a> and noticed that if pin 12 is set to an output and I run the Blink sketch on it, the built in led (supposedly connected to pin 13) blinks. It's not as bright as it is when I run it on pin 13, but nonetheless it blinks. If I run it on any other pin, nothing happens, which is the behavior I expected with pin 12.</p>
<p>Is this a common issue with arduino boards, the microcontrollers, etc. or did I get a bad board?</p>
<p>Overall the board visibly appears to have solid construction and appears as the one on the site that I linked to.</p>
<p>Lastly as a side note, I'm currently living in India and won't have a problem going back to their factory for a replacement, if it is a bad board. They include a 6 month warranty.</p>
<pre><code>int ledPin = 12;
int delayPeriod = 100;
void setup()
{
pinMode(ledPin, OUTPUT);
}
void loop()
{
digitalWrite(ledPin, HIGH);
delay(delayPeriod);
digitalWrite(ledPin,LOW);
delay(delayPeriod);
delayPeriod = delayPeriod + 100;
}
</code></pre>
| <p>See <a href="https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board">Have I bricked my Arduino Uno? Problems with uploading to board</a></p>
<p>As I state on that page, if pin 13 is set to input the LED may turn on due to being driven by an op-amp. A nearby pin turning on may be enough to cause that effect. Try adding:</p>
<pre><code> pinMode(13, OUTPUT);
digitalWrite (13, LOW);
</code></pre>
<p>See if that changes the behaviour.</p>
|
13873 | |arduino-uno|motor|arduino-motor-shield| | Arduino car on bluetooth remote appears to crash when motors started | 2015-08-01T23:37:51.413 | <p>I built a Arduino robot car which accepts instructions via bluetooth. The instructions are pretty simple, they tell the car to stop, go forward, reverse, turn left or turn right. </p>
<p>When I have the car powered through the computer USB (ie when I have just uploaded the sketch), all works fine. However, when I run off independent battery power, the arduino seems to restart whenever I give the car an instruction which means the motors have to operate.</p>
<p>I know the sketch is restarting inside the Arduino because the blue tooth terminal displays the startup text which is inside the 'setup' function.</p>
<p>What is going wrong here? What issue am I encountering?</p>
<p>The board is an Arduino UNO with an Arduino Motor Shield attached. The blue tooth and two sonic sensors are attached to the motor shield pins.</p>
<p>Also, I have a 9V battery attached to the motor shield. Plus 4 times 1.5V batteries powering the UNO. Am I screwing up the power at all? Getting too much? Or too little?</p>
| <p>You seem to be using your heavy-duty batteries for the Arduino and the light-duty 9 V battery for the motor. To me this seems backwards. Also the Vin pin to which you have the 9 V battery connected is by default connected to the Arduino as well. This means that if the motors draw a lot of current it will drag the Arduino's voltage down and it will probably reset (thus cutting power to the motors, and then it reboots). </p>
<p>From the <a href="https://www.arduino.cc/en/Main/ArduinoMotorShieldR3" rel="nofollow">Arduino Motor Shield page</a>:</p>
<blockquote>
<p>Vin on the screw terminal block, is the input voltage to the motor connected to the shield. An external power supply connected to this pin also provide power to the Arduino board on which is mounted. By cutting the "Vin Connect" jumper you make this a dedicated power line for the motor. </p>
</blockquote>
<p>You should cut that jumper so that the Arduino and the motor have dedicated supplies.</p>
<p>Also, arrange better batteries for the motor. You may find you can run the Arduino from the 9 V battery, and then make sure you have enough AA batteries to drive the motors.</p>
|
13876 | |memory-usage|rtc| | What will use less memory, an array or if ... else? | 2015-08-02T01:28:33.487 | <p>I'm trying to make my sketch smaller. Right now I use an array for the AM/PM part of my time display. My thinking is this makes it easy to change the formatting:</p>
<pre class="lang-c prettyprint-override"><code>char* ampms[]= {"am", "pm"};
void loop() // run over and over again
{ //get time from RTC
getDateDs1307(&second, &minute, &hour);
//change to 12 hour format.
if (hour>12) { hr = hour - 12; ampm=1; } else { hr = hour; }
//add leading 0 for hours
if (hr<10) { lcd.print("0"); }
//print hour in 12 hour format.
lcd.print(hr, DEC);
lcd.print(":");
//add leading 0 for minutes
if (minute<10) { lcd.print("0");}
//print minutes
lcd.print(minute, DEC);
//print am or pm using array.
dataFile.print(ampms[ampm]);
}
</code></pre>
<p>I could do this instead:</p>
<pre class="lang-c prettyprint-override"><code>void loop() // run over and over again
{ //get time from RTC
getDateDs1307(&second, &minute, &hour);
//change to 12 hour format.
if (hour>12) { hr = hour - 12; } else { hr = hour; }
//add leading 0 for hours
if (hr<10) { lcd.print("0"); }
//print hour in 12 hour format.
lcd.print(hr, DEC);
lcd.print(":");
//add leading 0 for minutes
if (minute<10) { lcd.print("0");}
//print minutes
lcd.print(minute, DEC);
//print am or pm using array.
if (hour>12) { lcd.print("am");} else {lcd.print("pm"); }
}
</code></pre>
<p>No more am/pm array. But, I have to add an if... is one better than the other for memory? Why?</p>
| <p>As Ignacio says, if the compiled size is the same both ways, look for something else. (But note that having the constants in flash memory (program memory) may still use about the same amount of RAM, and typically will take more program space.)</p>
<p>When I compile the code you showed (together with minor additions like declaration of variables) I show the array method using 4 bytes less code and 5 bytes more RAM than the <code>if</code> method, so there are tradeoffs.</p>
<p>You can replace the clunky <code>if</code> statement and its two <code>lcd.print</code>s with the following:</p>
<pre><code> lcd.print(hour>12? "am" : "pm");
</code></pre>
<p>Note that that line retains the two bugs that your <code>if</code> statement has, but it produces them more compactly. :) [One error is that your <code>if</code> statement prints <code>pm</code> for hours 0 through 12 and <code>am</code> for hours 13 through 23. Another error is that it prints zeroes instead of twelves for the hours after midnight and noon. More properly, a program should print like 12:xx am during hour 0 of the day, and like 12:xx pm, 1:xx pm, ... 11:xx pm during hours 12 through 23.]</p>
<p>Also note that as Gerben mentions, moving the "am" and "pm" strings into program memory via</p>
<pre><code>lcd.print(hour>12? F("am") : F("pm"));
</code></pre>
<p>saves 6 bytes of RAM. However, that improvement in RAM usage is offset by 74 additional bytes of program space! The following saves 6 bytes of RAM while increasing program size by only 12 bytes so may be preferable:</p>
<pre><code>lcd.print(hour>12? 'p' : 'a');
lcd.print('m');
</code></pre>
<p>The following lines of C can replace much of the code you showed. However, the <code>printf</code> library uses about 1300 bytes of program space, so the following compact-source-code approach cannot be recommended unless you are already loading some <code>printf</code> functions. It replaces the lines from <code>if (hour>12) { hr = hour - 12; } ...</code> to the end with</p>
<pre><code>enum { bufsize=8 };
char buf[bufsize];
snprintf (buf, bufsize, "%02:02%cm", hour%12, minute, hour>12? 'p' : 'a');
lcd.print(buf);
</code></pre>
|
13879 | |relay| | Arduino Relay Shield | 2015-08-02T05:37:13.000 | <p>I am wondering if this Arduino Relay Shield design would be good enough to handle 120v 1amp The transistor is a 2n4401. Also The Two capacitors on the other 3 circuits would be going to ground opps its to late for this <a href="https://i.stack.imgur.com/qC6go.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qC6go.png" alt="enter image description here"></a></p>
| <p>As already mentioned, everything to the left of the relays is completely irrelevant when it comes to what the system can cope with. It's purely down to the relays what voltage and current they can deal with. As far as the circuit goes there's nothing wrong with it that I can see at first glance.</p>
<p>So to go from there to an actual physical shield there are a number of things you do need to consider:</p>
<ol>
<li>Ensure that the relays have a rating <em>at least</em> as high as the expected maximum voltage and current, ideally <em>derate</em> it by <em>at least</em> 50%. For CFLs (which present an inductive load as well as a resistive load) you want to dereate it even more.</li>
<li>Ensure that the mains voltage track layout is kept well away from the low voltage digital signals and ground plane.</li>
<li>Ensure that the mains voltage tracks are sized appropriately and kept as short as reasonably possible. Use a track width calculator to get the right width.</li>
<li>Be sure to use appropriate connectors for the mains power. They need to be able to cope with as much current and voltage as the relays and at the same time be <em>safe</em>.</li>
<li>Keep all mains voltages away from human contact. This means no exposed live metal on the upper side of your board where it can be inadvertently touched. Any components with exposed leads that have mains voltage in them should have their leads insulated.</li>
<li>Be absolutely certain that, since this is a shield, no mains voltages even come close to the Arduino the shield is plugged into. This is especially critical around such areas as the USB socket where through-hole components (like screw terminal blocks) are likely to short circuit and cause very very nasty things to happen.</li>
</ol>
<p><strong>Remember: Mains voltages are dangerous, caution and safety should be your first concern over everything else!</strong></p>
<p>One more tip: Do all your mains experimentation as safe as possible. Either ensure that you have an <a href="https://en.wikipedia.org/wiki/Earth_leakage_circuit_breaker" rel="nofollow">ELCB</a> <em>and</em> an <a href="https://en.wikipedia.org/wiki/Residual-current_device" rel="nofollow">RCD</a> on your ring main / power outlet (with the former you must ensure that you have your earth wires connected properly), or even better (and what I would certainly recommend above all else), use an <a href="https://en.wikipedia.org/wiki/Isolation_transformer" rel="nofollow">Isolation Transformer</a> to separate you from the mains circuit entirely. With an Isolation Transformer electrocution is only possible if you contact <em>both</em> terminals at once as opposed to just one terminal of the normal mains supply.</p>
<p><strong>Edit:</strong> One thing that does puzzle me with your circuit is how you have wired up the common pin of the relays. That part of the circuit makes no sense to me at all. You should have 2 connections to each relay - <em>in</em> and <em>out</em> where <em>in</em> connects to the <em>NO</em> and <em>out</em> connects to the <em>common</em> pin¹. The only way your arrangement could work would be to designate one relay as a <em>master</em> power control and that one has the main power coming in which then feeds through to the common rail to supply the other three relays. If this is what you want, then you will have to ensure that the relay designated as master (and its connector) has <em>at least</em> three times the capacity of the other three relays and connectors (or all four relays have <em>at least</em> three times the capacity you would otherwise need).</p>
<hr>
<p>¹ Note: doing it this way around ensures that when the relay is in the <em>off</em> position the <em>NC</em> pin isn't live. The only pin that would ever be live is the <em>common</em> pin. Safety first...!</p>
|
13885 | |arduino-leonardo|ir| | IR frequency difference | 2015-08-02T11:16:40.083 | <p>I want to create a device that interfaces with the Light Strike Lasertag system using an Arduino Leonardo.</p>
<p>The Light Strike system uses not laser but regular infrared signals. According to a site that I found (<a href="http://www.meatandnetworking.com/projects/hacking-at-the-light-strike-laser-tag-game/" rel="noreferrer">http://www.meatandnetworking.com/projects/hacking-at-the-light-strike-laser-tag-game/</a>) it uses 37.8 khz signals. I only found IR-receivers using 37.9 or 38 khz. Can I use them? How far can the modulation frequency differ?</p>
<p>Is there anything else I need to watch out for when creating an IR-interface?</p>
| <blockquote>
<p>Can I use 37.9 or 38 kHz IR-receivers for 37.8 khz communication?</p>
</blockquote>
<p>Yes you can, it should be close enough. (I am assuming you are talking about some kind of prebuilt receiver that just receives the IR data and transmits it via RS232 or something like that)</p>
<hr>
<p>I'd suggest you'd use a phototransistor and a IR diode for the communication. You will have a lot more control over what frequencies you are operating on. Altho it might take a bit more work to program it, the end result will be exactly how you wish.</p>
|
13887 | |analogread|accelerometer| | XL335B accelerometer reports false readings | 2015-08-02T14:44:46.953 | <p>I'm using an XL335B accelerometer in a GY-61 breakout board. I'm powering the device using the UNO's built-in 3.3V power supply. The following code should convert the readings to m/s² (SI); however, it returns (-0.43|-0.52|-5.83) instead of the expected (0|0|-9.81) when lying untouched.</p>
<p><strong>Code:</strong></p>
<pre><code>const float CYCLE_LENGHT_MILLIS = 1000;
// REFERENCE_VOLTAGE 5 & STEP_COUNT 1024
// => VOLTAGE_STEP 0.0048828125
// MAX_ACC_VOLTAGE 3.3
// => MAX_ACC_VOLTAGE_STEP 675.84
// MIN_ACC_VOLTAGE 1.65 = 0.5 MAX_ACC_VOLTAGE
// => MIN_ACC_VOLTAGE_STEP 337.92
// MAX_ACC_MEASUREMENT 29.43 = 3g
// acceleration = (read()-MIN_ACC_VOLTAGE_STEP) * MAX_ACC_MEASUREMENT/(MAX_ACC_VOLTAGE_STEP-MIN_ACC_VOLTAGE_STEP)
//This can be simplified to: acceleration = read()*j - k
// => j = MAX_ACC_MEASUREMENT / (MAX_ACC_VOLTAGE_STEP-MIN_ACC_VOLTAGE_STEP)
// => k = MIN_ACC_VOLTAGE_STEP * j
const float j = 29.43/(675.84-337.92);
const float k = 337.92*j;
void setup(){
Serial.begin(9600);
}
void loop(){
Serial.print("(");
Serial.print(analogRead(0) * j - k); //X-AXIS
Serial.print("|");
Serial.print(analogRead(1) * j - k); //Y-AXIS
Serial.print("|");
Serial.print(analogRead(2) * j - k); //Z-AXIS
Serial.println(")");
delay(CYCLE_LENGHT_MILLIS);
}
</code></pre>
| <p>An effective but yet simple calibration is explained in <a href="https://chionophilous.wordpress.com/2011/08/26/accelerometer-calibration-ii-simple-methods/" rel="nofollow noreferrer">https://chionophilous.wordpress.com/2011/08/26/accelerometer-calibration-ii-simple-methods/</a></p>
<blockquote>
<p>We need to find the 0G mark and the sensitivity on each axis. Call them m_x, delta_x, m_y, delta_y, m_z, and delta_z (e.g. m_z is the zero-G mark or the “middle” on the z-axis, delta_z is the sensitivity on the z-axis). That makes 6 numbers, so we should expect to need at least 6 measurements.</p>
</blockquote>
<p>Check also the more accurate setup: <a href="https://chionophilous.wordpress.com/2011/08/26/accelerometer-calibration-iii-improving-accuracy-with-least-squares-and-the-gauss-newton-method/" rel="nofollow noreferrer">https://chionophilous.wordpress.com/2011/08/26/accelerometer-calibration-iii-improving-accuracy-with-least-squares-and-the-gauss-newton-method/</a></p>
<blockquote>
<p>Least-Squares</p>
<p>Here is the idea. We’ve been assuming that there are just six numbers we need to find to get a good calibration: m_x, m_y, m_z, delta_x, delta_y, and delta_z. Now matter how we place our sensor before we take readings, we assume it is still and is detecting exactly 1G of acceleration in some direction.</p>
<p>So if we read value x on the X-pin, y on the Y-pin, and z on the Z-pin we can look at the acceleration vector</p>
<p>If our measurements have no noise and our parameters are correct, the length of this vector should be exactly 1 no matter which way it is pointing</p>
</blockquote>
|
13888 | |interrupt| | Count RISING edges of a wave form by using ARDUINO | 2015-08-02T17:26:25.263 | <p>I have realised an electrical circuit that gives 5V in output. When I press a button, it gives 0V.
So I have in output a square wave (5V - 0V).
I would like to count how many times I press the button, by using an Arduino MEGA AT2560.
I have written this code below, but it doesn't work, because when I press the button, it increase the counter three or four times.
For example: I press the button 5 times, but the counter has arrived to 30!</p>
<pre><code>#include <SD.h>
#include <SPI.h>
unsigned int count_hall_f = 0;
void setup()
{
Serial.begin(9600);
attachInterrupt(0, interrFront, RISING); //18
}
void loop(){
}
void interrFront() {
count_hall_f++;
Serial.println(count_hall_f);
}
</code></pre>
<p>An example of the result is:</p>
<pre><code>1 <- I pressed here
2
3 <- I pressed here
4
5
6
7
8
9
10
11
12 <- I pressed here
13
14
15
16
</code></pre>
| <blockquote>
<p>I have choosen the values of R and C by experiments. Do you have a suggest for choose these values?</p>
</blockquote>
<p>I have a <a href="http://www.gammon.com.au/switches" rel="nofollow noreferrer">page about switches</a> - somewhat down the page is a discussion of debouncing, including some calculations which show how you can calculate the debounce time. With the switch pin pulled high by the internal pull-up (something you don't appear to be doing), and a 1 µF capacitor, that gives you a debounce of about 35 ms.</p>
<hr>
<p>Example schematic:</p>
<p><a href="https://i.stack.imgur.com/Px1on.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Px1on.png" alt="Hardware debounce"></a></p>
<p>Results on input pin:</p>
<p><a href="https://i.stack.imgur.com/IvUfI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IvUfI.png" alt="Debounce scope image"></a></p>
<p>(Maths supporting that figure on the above page).</p>
<hr>
<p>Note that it is important to have a pull-up or pull-down for your switch or it will read random values if not closed.</p>
|
13890 | |serial|arduino-leonardo| | Is there any problem about calling if (Serial) many times? | 2015-08-02T18:48:42.533 | <p>I am trying to debug a problem that I think may be related to the debug code itself and I tried to use theese macros:</p>
<pre><code>#define DEBUG_PRINT(x) { if (Serial) { Serial.print(x);} }
#define DEBUG_PRINTLN(x) { if (Serial) { Serial.println(x);} }
</code></pre>
<p>That works a bit but everything starts running really slow and my sketch get to hung up quite fast. Maybe it is timing related but does not seems like that.</p>
<p>if I change that by this the problem is gone:</p>
<pre><code>#define DEBUG_PRINT(x) { if (true) { Serial.print(x);} }
#define DEBUG_PRINTLN(x) { if (true) { Serial.println(x);} }
</code></pre>
<p>I'm using Arduino Pro Micro (Leonardo).</p>
<p>Is there any problem about calling if (Serial) so many times?</p>
<p>Full sketch <a href="https://github.com/aalku/Arduino_ESP8266_HttpServer/tree/debugQuestion" rel="nofollow">here</a> </p>
|
<p>The real flaw is testing if Serial is available all the time. For one thing, that wouldn't work on a Uno etc. How about something like this?</p>
<pre class="lang-C++ prettyprint-override"><code>// make true to debug, false to not
#define DEBUG true
// conditional debugging
#if DEBUG
#define beginDebug() do { Serial.begin (115200); while (!Serial) { } } while (0)
#define Trace(x) Serial.print (x)
#define Trace2(x,y) Serial.print (x,y)
#define Traceln(x) Serial.println (x)
#define Traceln2(x,y) Serial.println (x,y)
#define TraceFunc() do { Serial.print (F("In function: ")); Serial.println (__PRETTY_FUNCTION__); } while (0)
#else
#define beginDebug() ((void) 0)
#define Trace(x) ((void) 0)
#define Trace2(x,y) ((void) 0)
#define Traceln(x) ((void) 0)
#define Traceln2(x,y) ((void) 0)
#define TraceFunc() ((void) 0)
#endif // DEBUG
long counter;
unsigned long start;
void setup() {
start = micros ();
beginDebug ();
Traceln (F("Commenced debugging!"));
TraceFunc (); // show current function name
} // end of setup
void foo ()
{
TraceFunc (); // show current function name
}
void loop()
{
counter++;
if (counter == 100000)
{
Traceln (F("100000 reached."));
Trace (F("took "));
Traceln (micros () - start);
counter = 0;
foo ();
} // end of if
} // end of loop
</code></pre>
<p>That only does the Serial.begin() once, and the test for waiting for Serial to become available once.</p>
<p>Then, depending on the DEBUG define, the debugging code is executed or not. The fancy <code>((void) 0)</code> calls get optimized away completely by the compiler if DEBUG is false, thus making them have no effect if debugging is off (which wouldn't apply to your code).</p>
<hr>
<p><em>(Edited to add)</em></p>
<blockquote>
<p>As you can deduce from my macros I wanted to debug IF the serial port is connected. I don't want to wait for it to be connected.</p>
</blockquote>
<p>Well it wasn't <em>immediately</em> obvious from your code. In that case I suggest you test in the main <code>loop</code> function every second or so, to see if <code>Serial</code> is true. If so, set a flag. Test that flag in your debug function. That way you aren't slowing down every single <code>Serial.print</code> by 10 ms.</p>
<p>Like this amended code:</p>
<pre class="lang-C++ prettyprint-override"><code>// make true to debug, false to not
#define DEBUG true
// conditional debugging
#if DEBUG
#define beginDebug() do { Serial.begin (115200); } while (0)
#define Trace(x) do { if (serialConnected) Serial.print (x); } while (0)
#define Trace2(x,y) do { if (serialConnected) Serial.print (x, y); } while (0)
#define Traceln(x) do { if (serialConnected) Serial.println (x); } while (0)
#define Traceln2(x,y) do { if (serialConnected) Serial.println (x, y); } while (0)
#define TraceFunc() do { if (serialConnected) { Serial.print (F("In function: ")); Serial.println (__PRETTY_FUNCTION__);} } while (0)
#else
#define beginDebug() ((void) 0)
#define Trace(x) ((void) 0)
#define Trace2(x,y) ((void) 0)
#define Traceln(x) ((void) 0)
#define Traceln2(x,y) ((void) 0)
#define TraceFunc() ((void) 0)
#endif // DEBUG
const byte LED = 13;
bool serialConnected;
unsigned long timeSerialLastTested;
long counter;
unsigned long start;
void setup() {
start = micros ();
beginDebug ();
Traceln (F("Commenced debugging!"));
TraceFunc (); // show current function name
pinMode (LED, OUTPUT);
} // end of setup
void foo ()
{
TraceFunc (); // show current function name
}
void loop()
{
// every second, see if the Serial port is available
if (millis () - timeSerialLastTested >= 1000)
{
timeSerialLastTested = millis ();
serialConnected = Serial;
digitalWrite (LED, !digitalRead (LED)); // blink LED
}
counter++;
if (counter == 100000)
{
Traceln (F("100000 reached."));
Trace (F("took "));
Traceln (micros () - start);
counter = 0;
foo ();
} // end of if
} // end of loop
</code></pre>
|
13895 | |serial|usb|python| | Send numbers to arduino via serial port using python | 2015-08-02T21:03:35.407 | <p>I have a file with numbers called <code>fginputs.txt</code>. For example it could be something like this:</p>
<pre><code>4958
4154
4154
4154
4154
4154
4154
4154
4154
4154
4154
4154
4154
4154
4154
4154
4154
4958
</code></pre>
<p>I want python to send each number to arduino via serial port. After each number is received, arduino should print back an acknowledgment number, indicating that it got a valid number, and then store that number in a dynamic array, because I could create larger files. When there are no more numbers left, send a '-1' to finish transmission.</p>
<p>Here's my arduino code:</p>
<pre class="lang-cpp prettyprint-override"><code>// save some unsigned ints
uint16_t SIZE, *inputList, cont = 0;
boolean inputsReady = false;
void setup()
{
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
//free dynamic array memory
free(inputList);
//counter for how many numbers I've received starts at 0
cont = 0;
//This is true when there are no more numbers to receive, meanwhile false
inputsReady = false;
setupInputList();
}
/* If there's not enough space, resize the array by one unit and store the number
*/
void growAndInsert(int currentSize, int newInt){
if(currentSize > SIZE)
inputList = (uint16_t *)realloc(inputList, (currentSize + 1)*sizeof(uint16_t));
inputList[currentSize] = newInt;
}
/**
init inputList with 100 blocks
*/
void setupInputList(){
SIZE = 10;
inputList = (uint16_t *)malloc(sizeof(uint16_t) * SIZE);
}
void clearBuffer(){
while(Serial.available() > 0)
Serial.read();
}
/**
Listens in serial port for an integer that represents a new input and returns it.
If it doesn't get anything useful from serial, return 0
*/
int getNewInputFromSerial(){
if (Serial.available() > 0) {
delay(100);
// look for the next word
int cmd = Serial.parseInt();
clearBuffer();
if(cmd == 4958)
Serial.write("4");
else if(cmd == 4154)
Serial.write("5");
else
Serial.write("0");
return cmd;
}
return 0;
}
void loop()
{
if(!inputsReady){
int newInput = getNewInputFromSerial();
if(newInput == 0)
return;
if(newInput != -1)
growAndInsert(cont++, newInput);
else{
inputsReady = true;
//initTimer();
}
}
}
</code></pre>
<p>and the python script:</p>
<pre class="lang-python prettyprint-override"><code>global arduino
PORT = '/dev/ttyACM0'
FILENAME = "fginputs.txt"
#Read file with inputs
with open(FILENAME) as f:
content = f.readlines()
#init serial port
arduino = serial.Serial(PORT, 9600, timeout=1);
time.sleep(2);
#write
for input in content:
arduino.flush()
arduino.write(input)
time.sleep(.1);
resp = arduino.read();
print "i got " + resp
#Finish transmission with -1
arduino.flush()
arduino.write("-1")
#done
arduino.close();
</code></pre>
<p>The fist time I execute the script I get this:</p>
<pre><code>i got 4
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 4
</code></pre>
<p>Which is great. But if I run it a second time I get this:</p>
<pre><code>i got 0
i got 4
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
</code></pre>
<p>Which is terribly wrong because the file hasn't changed. I don't know what is going on here. If I unplug and plug back in the USB cable, transmission works flawlessly again.</p>
| <p>You could have a look at <a href="https://github.com/01org-AutomatedFlasherTester/pem" rel="nofollow">this</a>.</p>
<p>It's a python program which does record/playback of key-presses, through an UNO.</p>
<p>It already implements:</p>
<ul>
<li>serial communication with error checking</li>
<li>ACK: each message has its own ID, so you can keep track of what was lost, should anything bad happen</li>
<li>synchronization, in case your Arduino is powered up after the python program is started</li>
</ul>
|
13906 | |arduino-uno|components| | What requirements should components have to work with Arduino (UNO in particular) | 2015-08-03T13:51:37.277 | <p>I am fairly new to the whole concept of Arduino and electronic engineering in general.</p>
<p>Recently I bought myself an Arduino UNO and I'm wondering what "non off the shelf" components will work when I hook them up with the UNO. I have a lot of old electronic stuff laying around containing pushbuttons, sliders, faders, knobs etc. wich if possible, I'd like to take apart to connect them to the UNO for some fun fuzzin' around.</p>
<p>Many thanks in advance!</p>
<p>PS: this is my fist post ever on stackexchange so excuse me if the question is placed incorrectly or the tags are weird. Please DO correct me where I'm wrong.</p>
| <p>When it comes to electronics, hypothetically anything can be connected to anything else. The only real barriers are time, cost, and practicality.</p>
<p>Two major things to look out for though are voltage and current requirements.</p>
<p>Most Arduinos operate at 5 volts, so it's often easiest to connect it to other electronic devices which also operate at 5 volts. That certainly doesn't mean you <em>can't</em> connect an Arduino to something that operates at 3.3 volts (for example). However, it means you may need to add some voltage level conversion circuitry (although it's not always necessary, depending on the context).</p>
<p>Regarding current, a critical issue to look out for is how much current something will draw. For example, a motor will often require more current than an Arduino can safely provide. That means you'd need some kind of external power supply which can be switched by the Arduino.</p>
<p>The most valuable thing to do is to learn to find and read datasheets. These give information about electronic components, specifying things like voltage, current, timing and so on. For situations where there's no datasheet available, you may find it useful to learn how to use a multimeter and an oscilloscope to monitor how equipment behaves.</p>
|
13908 | |ethernet|time| | Arduino Ethernet Shield Response Process, Time, and Synchronization | 2015-08-03T13:57:42.410 | <p>I have a ethenet shield. I want to update my server page. Server page have to show current time. The code is given in this <a href="https://drive.google.com/folderview?id=0BzuMgxouJ695flY2M0JQWFJrd0F5NGthMXhSTUFkQ2xPV3RpdzJ6X2dRc05mdENYOXJnMWc&usp=sharing" rel="nofollow">link</a>. Code works but there is two problem</p>
<p>1- When i press the stop button in the browser, Arduino stops. After this i press refresh button and there is no response.</p>
<p>2- How can i synchronize the arduino time. From where? without setup another server. Is there any time stamp server that compatible with arduino? </p>
|
<h3>Question 1.</h3>
<p>Your code looks odd:</p>
<pre class="lang-C++ prettyprint-override"><code>void checkForClient(){
EthernetClient client = server.available();
if (client) {
boolean sentHeader = false;
while (client.connected()) {
if (client.available()) {
if(!sentHeader){
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();
sentHeader = true;
}
durumBildir(client,50,ID);
}
}
}
delay(1); // give the web browser time to receive the data
}
void durumBildir(EthernetClient client, int deger,String ID){
client.print(ID);
client.print("-");
client.print(deger);
client.print("-");
if (timeStatus()!= timeNotSet) {
digitalClockDisplay( client);
}
client.print("<br>");
}
</code></pre>
<p>You never <strong>read</strong> from client, so it will <strong>always</strong> be available (and thus you never leave your loop). I just tested it. Why are you sending the time out indefinitely? Even when you disconnect the poor Arduino is still sending the date and time out forever. No wonder you can't connect again.</p>
|
13909 | |arduino-uno|analogread|resistor| | Can I supply the board's 3.3V directly to the AREF pin? | 2015-08-03T14:00:36.307 | <p>Short dumb question: can I connect the 3.3V pin and the analog reference pin (AREF) directly?</p>
<p>I've heard mentions of a 32K internal resistor but I'm not willing to risk a short circuit without confirmation. Should I add an external resistor? Won't that create a voltage divider?</p>
|
<p>I don't see any big objection to connecting the 3.3 V pin to AREF, providing you take precautions in your code.</p>
<p>The default for AREF is so-called DEFAULT (heh) as here:</p>
<pre class="lang-C++ prettyprint-override"><code>uint8_t analog_reference = DEFAULT;
</code></pre>
<p>Once you do an <code>analogRead</code> the analogRead code connects up the desired analog reference:</p>
<pre class="lang-C++ prettyprint-override"><code>ADMUX = (analog_reference << 6) | (pin & 0x07);
</code></pre>
<p>Then it starts the ADC conversion.</p>
<p>If you <strong>change</strong> the analog reference voltage then this needs to be done <strong>before</strong> doing the analogRead. eg.</p>
<pre class="lang-C++ prettyprint-override"><code> analogReference (EXTERNAL);
analogRead (A0); // use external reference
</code></pre>
<p>The reason they do it this way is so that it is safe to physically connect up the 3.3V pin to the AREF pin, because the initial state of the processor is to <strong>read</strong> the AREF pin. </p>
<p>Once you do your first analogRead, and with the DEFAULT reference voltage used, you will find 5V at the AREF pin. If you had then connected that to something else like the 3.3V pin, it will short out and damage the board.</p>
<p>Example code:</p>
<pre class="lang-C++ prettyprint-override"><code>void setup ()
{
pinMode (13, OUTPUT);
delay (5000);
digitalWrite (13, HIGH);
int foo = analogRead (0);
} // end of setup
void loop ()
{
} // end of loop
</code></pre>
<p>Put your meter on AREF and you will see it jump to 5V after 5 seconds.</p>
|
13915 | |c++|temperature-sensor| | What's Wrong with this DHT22? | 2015-08-03T17:27:34.617 | <p>I made a circuit that takes humidity and temperature from DHT22 sensor and displays it on Lcd Screen. Simple enough but i get this error "Failed to read from DHT". That happens because i have this code </p>
<pre><code> if (isnan(t) || isnan(h)) {
delay(100);
Serial.println("Failed to read from DHT");
} else {
delay(100);
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.println(" *C");
//lcd.print("Temp: ") ;
//lcd.print(t);
//lcd.setCursor(0, 1);
//lcd.print("Hum: ") ;
//lcd.print(h);
}
</code></pre>
<p>So the values are <strong>NaN</strong> . But 1 minute before it worked fine, and now again it doesnt. Everything is soldered the right way and nothing is false. Lcd is wired ok and it works but i dont get values from DHT22.</p>
<p>Here are some pics to help you out.
<img src="https://i.stack.imgur.com/ZG3Hi.jpg" alt="Overview">
<img src="https://i.stack.imgur.com/yEfbl.jpg" alt="Wiring">
<img src="https://i.stack.imgur.com/KvYZu.jpg" alt="Wiring"></p>
<p>In the third Image we see its working. And now its not!
is the DHT sensor broken?</p>
<pre><code> #include "DHT.h"
#include <LiquidCrystal.h>`
#define DHTPIN 2
#define DHTTYPE DHT22 // DHT 22 (AM2302)
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
Serial.println("DHT22 test!");
lcd.begin(16, 2)
dht.begin();
}
void loop() {
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(t) || isnan(h)) {
Serial.println("Failed to read from DHT");
} else {
lcd.print("Hum: ");
lcd.print(h);
lcd.setCursor(0, 1);
lcd.print("Temp: ");
lcd.print(t);
}
}
</code></pre>
<p>Thats my code by the way</p>
| <p>Two things:</p>
<ol>
<li>You need to put a delay in between your read requests. Currently you're reading way too fast, every few milliseconds you're hitting the DHT. Max interval should be every two seconds or so. </li>
<li>Add a 10k resistor between pin 1 and 2 of the DHT. </li>
</ol>
<p>I'd bet adding a delay, or using the simpleTimer library to control how frequently you read from the DHT will clear this up. </p>
|
13918 | |arduino-uno|i2c|lcd| | MCP23017: 16x2 LCD showing black boxes | 2015-08-03T20:04:46.003 | <p>I've researched a lot but I couldn't find a solution to my problem, which is that after properly following all steps from this Website: <a href="http://www.danielealberti.it/2014/02/collegamento-diplay-lcd-ad-arduino-via.html" rel="nofollow">http://www.danielealberti.it/2014/02/collegamento-diplay-lcd-ad-arduino-via.html</a></p>
<p>and after using the Library LIQUIDTWI2:</p>
<p>(<a href="https://drive.google.com/file/d/0BwSP1-P3E2UJY1loYWtWQVRWNlU/edit?usp=sharing" rel="nofollow">https://drive.google.com/file/d/0BwSP1-P3E2UJY1loYWtWQVRWNlU/edit?usp=sharing</a>)</p>
<p>for I2C connections, the LCD keeps displaying black boxes on the top row. </p>
<p>I'm pretty sure that I have wired (as shown in the tutorial linked above) and programmed everything correctly but I'm still getting the black boxes. Is the problem related with the MCP23017 pin expander or with something else?</p>
<p>I'm using an Arduino UNO</p>
| <p>Quite often such situation occurs when the display does not reset properly (the reset from the IDE does not necessarily reset the display!). </p>
<p>So, once the sktech has been uploaded to the board, I would first try to do a reset on the Uno board (using the RESET button). If that doesn't do the trick, I would recommend to make the contrast adjustable (all my LDC displays showed "black boxes in the upper row" on delivery and I had to ajust the contrast).</p>
<p>If that also has not the desired effect, there is no alternative to debugging your code. Without the code itself, we cannot guess what might be wrong.</p>
|
13923 | |shift-register| | Simple Arduino - 74hc595 shift register construction [tmli5] | 2015-08-04T00:11:32.433 | <p>I'm quite new to Arduino world and I'm trying to understand how shift registers work.
I built this construction :
<a href="https://i.stack.imgur.com/dmFiN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dmFiN.jpg" alt="enter image description here"></a></p>
<p>In fact, it is an Arduino Duemilanove with AtMega on it, but afaik it doesn't matter.</p>
<p>The tutorial I try to follow use SPI library so I try to do it too. I kind of understood that data input, latch and clock had to be pins 7, 4 and 11.</p>
<p>Basically, all I try to do is sending a byte to light the LEDs. As for me now, the sequence should light all LED, then no one, then one after another.
I know there is one more input ont the right side of the SR but I didn't plan this model so I ran out of LEDs...</p>
<p>This is the code I use :</p>
<pre><code>#include <SPI.h>
#include <StandardCplusplus.h>
#include <vector>
#include <iterator>
#include <size_type>
using namespace std;
//pin du shift register
#define DATA_PIN 13
#define LATCH_PIN 4
#define CLOCK_PIN 11
//à utiliser plus tard
#define INPUT_PIN 2
void setup() {
pinMode(DATA_PIN, OUTPUT);
pinMode(LATCH_PIN, OUTPUT);
pinMode(CLOCK_PIN, OUTPUT);
//pinMode(INPUT_PIN, INPUT);
SPI.setBitOrder(MSBFIRST);
SPI.setDataMode(SPI_MODE0);
SPI.setClockDivider(SPI_CLOCK_DIV2);
SPI.begin();
//SPI.transfer(getBit(3));
//digitalWrite(LATCH_PIN, HIGH);
//digitalWrite(LATCH_PIN, LOW);
Serial.begin(9600);
Serial.println("start !");
}
void loop() {
shift(B11111111);
shift(B00000000);
shift(B10000000);
shift(B01000000);
shift(B00100000);
shift(B00010000);
shift(B00001000);
shift(B00000100);
shift(B00000010);
shift(B00000001);
}
void shift(int n){
SPI.transfer(n);
digitalWrite(LATCH_PIN, HIGH);
digitalWrite(LATCH_PIN, LOW);
Serial.print("shift : ");
Serial.println(n);
delay(1000);
}
</code></pre>
<p>When I upload this code, LEDs sequence has no sense, but serial output was totally OK.</p>
<p>What I see (without the output 0 of course) is :
1111111, 0111111, 1011111, 1110111, 1111101 and then 1111111 without further changes, whereas serial output is 255, 0, 128, 64, 32, 16, 8, 4, 2, 1, 255, 0, 128 and so on.</p>
<p>I assume I didn't understand something important, and it prevent me from finding answers in google.</p>
<p>Thanks for helping, it's really disturbing for me.</p>
<p>EDITS : </p>
<p>changed the title, it is a 74HC595.</p>
<p>Strangest behavior too (not gonna create another topic for that now), I dont have to connect both the gnd and VCC from my arduino for this to light LEDs. It changes a little the brighness of LEDs, but surprisingly VCC< GND< both</p>
<p>This is the tutorial I use to understand shift registers : <a href="https://youtu.be/6fVbJbNPrEU?t=195" rel="nofollow noreferrer">https://youtu.be/6fVbJbNPrEU?t=195</a>, and the one that uses SPI is nXl4fb_LbcI</p>
<p>I am now aware that I should get one resistor for each LED but I don't have that much resistors and as far as I can see this don't harm my LEDs nor underpower them.</p>
|
<p>You have a number of problems here. The first is the wiring.</p>
<p><a href="https://i.stack.imgur.com/idHuy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/idHuy.png" alt="595 wiring diagram"></a></p>
<p>My wiring diagram above is for the Uno / Duemilanove. Since that is what you have, you should follow that.</p>
<p>The pins are fixed in hardware, except for the slave select pin. Thus D13 on the Duemilanove should go to pin 11 on the 595. D11 on the Duemilanove should go to pin 14 on the 595. And your slave select (which may as well be pin 10 on the Duemilanove) should go to pin 12 on the 595.</p>
<hr>
<p>Your code looks more complex than it needs to be. This code will exercise the 8 LEDs:</p>
<pre class="lang-C++ prettyprint-override"><code>#include <SPI.h>
const byte LATCH = 10;
void setup ()
{
SPI.begin ();
} // end of setup
byte c;
void loop ()
{
c++;
digitalWrite (LATCH, LOW);
SPI.transfer (c);
digitalWrite (LATCH, HIGH);
delay (20);
} // end of loop
</code></pre>
<hr>
<p>As other responders have said, you should have a current-limiting resistor for <strong>each</strong> LED. You can't share it like that.</p>
<p>Also the 595 ground (pin 8) should be wired to the Duemilanove ground, not via a resistor.</p>
<hr>
<h2>Reference</h2>
<p><a href="http://www.gammon.com.au/forum/?id=11518" rel="nofollow noreferrer">Using a 74HC595 output shift register as a port-expander</a></p>
|
13929 | |arduino-due| | Using arduino Due for camera control | 2015-08-04T04:12:07.873 | <p>Could the arduino Due take and send image data from 5MP camera module to PC in the following condition? </p>
<ul>
<li>frame rate = 1fps </li>
<li>resolution = 2592 x 1944 </li>
<li>format = 10 bit bayer raw RGB</li>
<li>interface : parallel ports (DVP) between camera and Due
spi between Due and PC(or SD card)</li>
<li>FIFO(frame buffer): would not be used </li>
<li>SDRAM: would not be used
(But if it is needed, I would SDRAM via spi. Also I can use a frame buffer like AL422B. But if it is possible I would avoid using them.)</li>
</ul>
<p>The camera would send 50Mbit image data per second and they will be transferred via 8 parallel lines(D0~D7) to the Due. And then they would go to PC directly or after passing SDRAM. But how can one evaluate if the 84Mhz is enough to do this job by calculation? </p>
<p>Arduino Due specs
<a href="https://www.arduino.cc/en/Main/arduinoBoardDue" rel="nofollow">https://www.arduino.cc/en/Main/arduinoBoardDue</a></p>
<p>camera module example (OV5642)
<a href="http://www.uctronics.com/cmos-camera-adapter-board-for-omnivision-image-sensor-p-248l.html" rel="nofollow">http://www.uctronics.com/cmos-camera-adapter-board-for-omnivision-image-sensor-p-248l.html</a>
But this is not what I want to use. In my project I need to build a camera module and it would not include FIFO unless it's highly recommended. </p>
| <p>So a quick feasability assessment:</p>
<p>2592 W * 1944 H * 10 bit = 50388480 bits</p>
<p>50388480 bits / 8 bit data bus = 6298560 packets</p>
<p>84000000 clocks per second / 6298560 packets = ~13 clock cycles per packet</p>
<p>I think that by itself, from a purely data perspective, without looking too deep into datasheets, you could feasibly read data from a port and push it out the USB port, and clock the data in less than 13 cycles. But what this means is you'd have to get into the nitty gritty of the processor and figure out how to do that as low level as possible because <code>DigitalRead()</code> and <code>Serial.print()</code> aren't going to cut it as they won't be fast enough.</p>
<p>The real challenge is that the above totally depends on being able to clock the data from the sensor yourself, which if I recall correctly, these sensors can actually be pretty picky about their clock.</p>
<p>I would highly recommend a FIFO, that way the sensor data can be clocked to it as fast as it wants to be clocked, and then you could read from the FIFO at your own pace as it will clock data out at exactly the rate you want it. Also 1 FPS is a pretty lofty goal if you are only a beginner. Like I said, it is probably possible, but it requires a lot of optimizations and planning that are not very straightforward to implement, especially if you are just starting out.</p>
|
13933 | |arduino-mega|usb|uart| | Arduino Mega as a USB device | 2015-08-04T10:42:08.283 | <p>My need is to connect an Arduino board (any board that has around 3 UARTs support) to a host PC via USB and expose the 3 UART connections as 3 USB devices (say /dev/ttyUSB0, /dev/ttyUSB1, /dev/ttyUSB2) in the host PC. From my search, I found Arduino Mega 2560 supports upto 3 UARTs. My question is can we expose these UARTs into individual USB ports to the host system?</p>
<p>Thanks,
Alexander</p>
| <p>Not directly, no. You have basically have 4 UARTs on the Mega2560 - one of them (USART0, pins 0&1) is connected to the USB interface chip, and the others are left unassigned for you to use as you like. It's the USB interface chip that is being seen in your computer as /dev/ttyUSB0, not the UARTs in the Mega2560 chip.</p>
<p>That's not to say that what you are after is not possible - it is perfectly possible, but it will require some clever programming on your part. You will need to:</p>
<ol>
<li>Define a protocol that will multiplex 3 streams of serial data through the one USB serial connection</li>
<li>Write a sketch that works with that protocol to direct the incoming data to the right UART ports and multiplex the UART traffic into the protocol stream you have defined</li>
<li>Write software on your computer to perform a similar task - read in data and multiplex it, and read the multiplexed data stream and split it out to three separate destinations.</li>
</ol>
<p>What the destinations on the PC end can be is a bit of a wooly area. If you want to make it look like serial ports in /dev then you can use a <em>pty pair</em>, which is a master/slave pair of pseudo TTY devices that you can use to pass data through. On most Linux systems they are numbered devices in /dev/pts, so /dev/pts/1 would be an example.</p>
<p>The function <a href="http://man7.org/linux/man-pages/man3/openpty.3.html" rel="nofollow"><code>openpty(...)</code></a> creates and opens a pty pair for you to use in your program. You would do that 3 times to make three pairs and each one would be the endpoint to a sub-stream in your multiplexed data.</p>
<p>For instance, here is a bit of code I use to open a pty pair:</p>
<pre><code>struct termios options;
openpty(&_masterfd, &_slavefd, _dev, NULL, NULL);
fcntl(_masterfd, F_SETFL, 0);
tcgetattr(_masterfd, &_savedOptions);
tcgetattr(_masterfd, &options);
cfmakeraw(&options);
options.c_cflag |= (CLOCAL | CREAD);
if (tcsetattr(_masterfd, TCSANOW, &options) != 0) {
fprintf(stderr, "Can't set up PTY\n");
}
</code></pre>
<p>That makes it appear to almost be a serial connection in style. Of course you don't have the concept of a baud rate over a pty connection, so it will be down to your software to define how you control the baud rate (probably easiest to have it hard coded to the baud rates you need).</p>
<p>In that snippet you talk internally to the <code>_masterfd</code> with normal <code>read()</code> and <code>write()</code> functions as you would any other device or file. Some other piece of software would open the other end of the pty pair (the <code>_slavefd</code>), the name of which is placed in <code>_dev</code> when the pty pair are opened. You could use that <code>_dev</code> name to then create a symbolic link to a better named device instead of using the <code>/dev/pts/x</code> name that could change without warning from one run to the next.</p>
|
13948 | |power|avr|float| | Float arithmetic vs. int arithmetic - is there any power penalty? | 2015-08-04T19:58:11.810 | <p>It is widely known that float arithmetic takes longer (that is, eats more cycles) than fixed-point (or integer, or bitwise arithmetic), and that surely is something to consider for speed- and time-critical applications.</p>
<p>My question is: supposing I don't have any time-critical need (and I have enough program and RAM memory), should I be worried by any other disadvantage of using <code>float</code>?</p>
<p>Specifically, I wonder if the processor would be more power-hungry because of those extra CPU cycles.</p>
<hr>
<p>UPDATE: What will my application do meanwhile?</p>
<p>The only goal of the application is to turn lights on and off (lots of them) based on push-button input. I am using <code>float</code> to apply filtering to button inputs, in order to <a href="http://forum.arduino.cc/index.php?topic=125297.0" rel="nofollow">debounce the buttons simulating a RC filter + schmitt-trigger</a>. So the loop in pseudo-code would be:</p>
<ol>
<li>Read all inputs (digitalRead or direct port access);</li>
<li>Filter the readings and decide if a button action has been detected;</li>
<li>Set some control flags that determine which part of the cycle the lights are in;</li>
<li>Check for elapsed time to actually turn blinkers on and off.</li>
</ol>
<p>So, since I plan to react to button input as realtime as possible, most time would be spent filtering (that is, performing floating point operations), since direct port access and flag-setting are supposed to be nearly instantaneous, right?</p>
| <blockquote>
<p>The only goal of the application is to turn lights on and off (lots of them) based on push-button input. I am using float to apply filtering to button inputs, in order to debounce the buttons simulating a RC filter + schmitt-trigger. </p>
</blockquote>
<p>Using floats is <strong>way</strong> overkill here. To debounce all you need to do is note when the switch changed state, and ignore further state changes during a certain interval, say 10 ms. It is even quite feasible to sleep during that debounce period. One of the watchdog timer intervals is 16 ms which would be about right for that.</p>
<p>In any case, an application that turns lights on is hardly going to be one where you are worried about how much power floating point operations take. I would be 1000 times more worried about how much power the lights use.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.