text:
What are the consequences of different clock speeds on different boards?
I am a programming amateur, arduino noob, trying to decide which board will be better for my project. I need a small board. I am trying to decide between the Teensy 3.2 and the RFduino. I want to have blue-tooth capability for over air routine changes to a WS2812B LED strip, which makes the RFduino attractive because of its integrated BLE4.0 antenna. However, I want to be able to have enough speed for imperceptible LED modulation, which makes the 72MHz speed of the Teensy attractive.
What would be the objective difference between the 16MHz processor on the RFduino versus the 72MHz on the Teensy3.2? Is this something I should be concerned with?

What sort of LED strip?

Planning on 3M of 60LED/M WS2812B strip as of now.

You'll have to set some kind of timing requirement. Like: I want to be able to send and execute a bluetooth message in .. milliseconds. That's where it gets interesting. You might come to the conclusion that bluetooth is the limiting factor (thus a higher clock speed won't help a thing).

On the LED strips, the WS2812B's have a fixed timing, so a faster processor != faster LED strip you might try a "DotStar", SPI-controlled or APA102 led strip. In that case, faster SPI = faster LED strip. But those strips need 64 extra bits and 8 bits extra per LED.

You have to set your requirements, or atleast elaborate what you want to achieve.
Best would be to program in a set amount of effects on the microcontroller and only send which effect you want to "start" with maybe even a color.
But you have to specify stuff, you should make a list like this:
Length of messages
(Max) baudrate of bluetooth device & microcontroller

amount of bits in the total LED strip
speed of sending bits into the LED strip

Maximal time from sending to effect

Sample calculation for NeoPixel (WS2182)
If you can make a good approximation (or find actual values) you can determine which speed you are going to need. This might even be 1Mhz, try to avoid premature optimization.
60 leds/m for 3M = 180 leds.
24bit data per LED.
180*24 = 4320 bits of data.
One bit takes around 1,3uS, so 4320*1,3 = 5616 uS
Which is 5,616 milliseconds to update the LED strip. (Processor Mhz won't help you here)
Sample calculation for DotStar (APA102)
180 leds, 32bit per LED = 5.760 bits total.
+64 bits (32bit start frame, 32bit end frame).
5824 total bits.
You can set the SPI clock divider to 2.
So if your board runs at 16Mhz, divided by 2, you get 8Mhz SPI output.

8 megahertz = 8 000 000 hertz

(EDIT)

The fastest rate is "divide by 2" or one SPI clock pulse every 125 nS. - Nick Gammon (http://www.gammon.com.au/spi)

Neopixels take 0.85us + 0.4us = 1,25 us (1250ns).
So they would be 10x slower.
(never mind this calculation, it was from before using Nicks' facts)
8.000.000  |  5824
 1 sec     |   x

(Your x value will be the time in seconds to update the DotStar strip with SPI@8Mhz)
What was your point?
After this you can check your baudrate + message length to see how long sending/receiving your message will take.
You can then reliably tell if you need 1, 8, 16 or 72Mhz.
I believe the DotStar led strips should be faster, but I haven't completely calculated it out. You could ask yourself if it's worth trying to omptimize that.
BUT, note that the DotStar/SPI led strip allows you to have "interrupts". Which means you can receive characters over the bluetooth while you're writing to the LED strip.
And, we're probably overthinking the situation. But it's better to overthink it using hard values :)

As was mentioned earlier about the DotStar LED strip/led
There is one thing missing in the calculation above. The End Frame shows as a 32 bit frame of all 1's. That is almost correct. The least obvious is that you need to add 1/2 of a bit for each led in the strip. This is due to the way that the clock is sent down the line. So the 180 led strip would require 90 bits in the End Frame. If you don't do this you will have some of the leds at the end that are not reacting correctly. I know this sounds strange, had me for a while (I use Raspberry Pi).
Also, I have seen where some have tested the SPI mode of sending the data down the line and managed to achieve about 16Mhz clock speeds. Great for POV display.
The DotStar don't require refreshment at all. Each LED has it's own PWM chip built in. They are more expensive than the Neopixel, so it depends on the application as to which is better for you. I loaded my string with colors and then disconnected the data lines (led strip on different power supply) and turned off my Pi. Yup, the DotStars stay as they are.
It has been said they are 'addressable' which is not truly accurate. When sending data, it is the first one, then the second and on. If you wanted, you can change only the first few. Odd hack. Just send the Start Frame (32 or more 0's) and start sending data to the first without affecting the rest of the strip. Note: you might have to account for the 1/2 bit clock loss. eg: 1 bit per 2 leds.
Here is a pretty good description of the DotStar functionality :
https://cpldcpu.com/2014/11/30/understanding-the-apa102-superled/
Here is a Youtube tutorial (2 short videos) that helped me quite a bit:
https://www.youtube.com/playlist?list=PLhXSL6B3uLd551fEQlQGd3LrhzvudKfJQ

You would think on the face of it that a faster processor will give you "more speed" however that does not necessarily work in a linear way. The faster processors tend to have more sophisticated chips. And "more sophisticated" can be code for "it takes more clock cycles to achieve the same thing".
I have code that drives 300 NeoPixels in a seamless manner, on a 16 MHz Arduino Uno, however during the driving it is pretty processor-intensive (and interrupts have to be off). So certainly you can have some smooth effects at 16 MHz. However controlling them in real time, via Bluetooth, may be a different thing.
NeoPixels will "remember" the last thing that was sent to them, so (when interrupts are active) you could be accepting new instructions, and the pixels will just display what they were last sent. This may be acceptable for you.
The Adafruit page for RGB LED Strip mentions that their library is only for the AVR processors. So that may be a consideration for you.
Even with other display strips, you may find that, during reception of radio signals, the strips cannot alter their patterns at high speed. The 72 MHz you quoted is only 4.5 times as fast as 16 MHz. The NeoPixel timings are in the order of nanoseconds (350 ns for a zero-bit) so timing is tight. Having 4.5 x the clock speed isn't necessarily going to give you enough leeway to do radio communications.

I just want to be able to select and change the program remotely via BLE, rather than send sequential commands over air. Does this change your answer at all?

Your design seems to me to consist of two components:

Showing some pattern
Receiving a new pattern (or code for a new pattern)

You can't be doing both at precisely the same time. (Maybe with two processors you might - one doing the radio, and one displaying the pixel pattern). I found I could refresh 1000 pixels in 63 ms, which is roughly 16 FPS. If you have less pixels it will be faster. I don't know exactly how long it takes to determine if a Bluetooth message has arrived, I assume not particularly long.

Planning on 3M of 60LED/M WS2812B strip as of now

So, 180 pixels. At 63 µs per pixel that would be 11.3 ms to refresh the strip. You can see that this gives you quite a bit of time over in one second to receive new instructions.

I see now that I should elaborate more on "real-time". I just want to be able to select and change the program remotely via BLE, rather than send sequential commands over air.  Does this change your answer at all? Edited in original question.
Also added the LED IC spec -- could you confirm that WS2812B "remembers"? I have only found literature that LPD8806 "remembers" as you describe.

Certainly the WS2182 pixels that I have a page about here (amongst lots of pages that other people have) remember the setting. If you disconnect the Arduino (but leave power to the pixels) they retain the last setting. That's how they are designed. A 10 µs (or so) gap in sending any bits latches the previous setting. Once latched it stays there indefinitely.

@aeolus you only have to write to the strip when you want to change it. If everything would be lost immediately, you wouldn't be able to work with these strips ;)


text:
Arduino to Thingspeak using WiFly-RN171 (Firmware 4.0)
I am attempting to use an Arduino Uno+WiFly setup to send data to Thingspeak.
I have tried a few libraries by now. But nearly all of them don't have a working WebClient example (WebServer works fine).
I am using Arduino 1.6.3 IDE for Arduino UNO R3 + Wifly-RN171 with Firmware 4.0
The libraries I have tried (found through Google and forums):

https://github.com/sparkfun/WiFly-Shield/tree/master/Libraries/Arduino
A ThingSpeak example is given but the execution stops when WiFly.begin() is called. I tried WebClient and WebClient(Faster) examples from the same library and they are both stuck at the same line: WiFly.begin().
I believe this could be compatibility issue (WiFly firmware version/Arduino) but am unsure how to fix it.

Note: There seems to be a few versions for the SparkFun WiFly library from my search results. I tried whatever I found but only listed the latest one since if it is indeed a compatibility issue a newer version should be more likely to work.
https://github.com/Seeed-Studio/WiFi_Shield
This one has a http example which I am attempting to use to send data to Thingspeak through http get/post. I am getting 'Bad Request' from their nginx server. Any help in the right direction will be much appreciated.
I hosted the sketch I tried here: codebender.cc/sketch:276925

p.s. I am not allowed to post >2 links due to reputation so the last one is plain text.
p.s.s Can someone with higher reputation help me add the new tags {thingspeak, wifly, rn171}

I solved my problem by sending a GET request to a hosted PHP script which in turn updates Carriots by means of a Curl request.
My PHP Script
<?php
$humidity=$_GET['humidity'];
$data = array("protocol"=>"v2", //Compose JSON stream
              "at"=> "now",
              "device"=>"DEVICE_NAME",
              "data" => array ("humidity" => trim($humidity)),
              "checksum" => "");
$data_string = json_encode($data);

$ch = curl_init('https://api.carriots.com/status'); //Compose the HTTP request
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'carriots.apikey: YOUR_API_KEY',
    'Content-Length: ' . strlen($data_string))
);

$result = curl_exec($ch); //Send the stream

Note:

I switched to Carriots from ThingSpeak due to personal preference.
This is by no means a standard way to send stream to Carriots.This
involves additional effort which slows down transmission of data but
I decided that this setup will be enough for a hobby project.
A good understanding of how POST requests are built should allow me
to skip the extra PHP script completely.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
How do we connect 2 FSR sensors to an Arduino Mega?
One can connect an FSR sensor (a force-sensitive resistor) to an Arduino via 5V, Gnd,  and A0 port (as below, according to an adafruit.com page), but how will it work for two of them instead of one?

Attach the second FSR mostly the same as the first, but connect the second analog voltage to A1 instead of to A0.
You can use several copies of  the circuit (below left) with each circuit's analog voltage going to a different analog-converter input (A0, A1, A2, ...).

To connect up multiple 5V and ground connections, you can:
•  use almost any popular shield
•  use breadboards like those illustrated above
•  cut and solder Dupont cables to add extra pins or sockets in or out (for example, cut two M-F Duponts in half, and connect both F halves to one M half)
•  connect to the extra 5V and Gnd pins on Uno or Mega boards.  (On a Mega, besides 5V and Gnd pins on programming headers, there are two 5V sockets next to 22 and 23, and two Gnds next to 52 and 53.)
The diagrams above right show the location of the 5V pins on the programming headers found on the Uno.  Most Arduino boards have at least one AVRISP header like that.

What about the Ground pin and the 5V? there only 1 5V

@user19846 see edit

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
How to control relay using SIM800 and Arduino Mega through SMS?
For my project I need to control relays through SMS and now I can send SMS from my SIM800 module which is connected to Arduino Mega R3. But I tried several shapes for AT commands to receive SMS and parse it to check sender number and SMS text but every time I received a 2 digits number in serial monitor of Arduino,

Post your code.

In below page I found a code which can solve my problem with some modification but when I tried to compile it, there was an error which has displayed gt is not declared in this scope. and I could not find out what gt usage is

LINK: http://www.ayomaonline.com/iot/sim800-controlling-arduino-with-sms/

Replace every > with > and it should work.

Probably something wrong with the website, since > is the HTML entitie for >

thanks for your comment, I had changed the gt symbol with > and &lt with < there is not any error after modification but still not any response when SMS receive

Update your post with the code you have now.

and based on these modifications the code is pasted below:

} else if (lastLine.length() > 0) {
if(nextLineIsMessage) {
Serial.println(lastLine);
if(lastLine.indexOf("LED ON") >= 0){
ledStatus = 1;
} else if(lastLine.indexOf("LED OFF") >= 0) {
ledStatus = 0;
}
nextLineIsMessage = false;
}
}
for( int i = 0; i < sizeof(currentLine);  ++i ) {
currentLine[i] = (char)0;
}
currentLineIndex = 0;
} else

Since code was too long to update here so I had to paste some parts of it. for checking please paste complete code from above link then in void loop do necessary modifications by finding and replacing > with > AND < with <

with below code I could receive sms but still seeking a way to parse it

#include <SoftwareSerial.h>
// software serial #1: TX = digital pin 10, RX = digital pin 11
SoftwareSerial SIM800(10, 11);
void setup()
{
SIM800.begin(19200);
Serial.begin(19200);
SIM800.write("AT+CMGF=1\r"); //set GSM to text mode
delay(1500);
SIM800.write("AT+CPMS="SM"\r"); //Preferred SMS Message Storage
delay(1000);
while(0!=SIM800.write("AT+CNMI=1,2,0,0,0\r\n")){
SIM800.write("AT+CMGR=1\n\r"); //list the first message from SIM Memory
SIM800.write("AT+CMGD=1\r");
}
while(1)
{
if(SIM800.available())
{
}
}
}
void loop()
{
}


text:
How can we replace a 10k potentiometer with resistors?
I am using an LCD (16x2) with an Arduino Uno R3, in for that I need a 10 kΩ potentiometer, but I don't have it now. How can I replace that?
I have resistors of many kinds and a 1 kΩ potentiometer.

Just use your 1k pot in place of the 10k pot. The resistance doesn't matter that much (though you don't want to go loo low or you could draw too much current) since it is just being used as a voltage divider to set an offset point for the LCD.

"though you don't want to go loo low" just to be sure: a 1k pot can go as low as a 10k pot, right? Like from 0 to 1k rather than from 0 to 10k, and the zero being the lowest value?

No. Like using a 100 ohm potentiometer. It's the total pot resistance that determines the current drawn from Vee.

Ah, you wrote "voltage divider", so that connects all 3 pins of the pot of course. Thanks!

I tried it but the brightness is too high so that the letters are not visible.

Derived from Ohm's Law:

R = R1 + R2 + ... + Rn (For resistors in Series)
(1/R) = (1/R1) + (1/R2) + ... + (1/Rn) (For resistors in Parallel)

You can use any resistance from 1k to 10k with your LCD but the actual value depends on your choice and preferences. You may start with 5k and if you have one then its allright. But if you do not have a resistor of that value you can join resistors of lower values in series with your 1k POT to get resistance of 5k ~ 6k.
In such a way you may get a variable resistance (1k pot) with a suitably high value (other resistors in series). If you wish, you may add more resistors to get higher values like 8k ~ 9k and so on.

Try using 9k~1k. (It worked for my 16*2 LCD)
Or place 9k in series with 1K and vary that.
Connect 10 of your 1K resistors in series. Connect one end to GND and other end to VCC. Now, you will have 10 different nodes (including VCC and GND) each having a different voltage. Connect your desired input pin to any of those nodes.

can you please decribe the circuit(resistors)?

Ok. Connect 10 of your 1K resistors in series.
Connect one end to GND and other end to VCC. Now, you will have 10 different nodes (including VCC and GND) each having diff. voltage. connect you desired input pin to any of that node.

copt-ied past-ed same sentence? :)


text:
Is cheap away arduino trustworthy
I have recently decided to buy an arduino over a raspberri pi and have been shopping for a good deal and learning about which model I need and where to buy.
I have come across a few very cheap arduino uno boards that are identical to every other board. These range from an unbelievable $4-$15. Are they officially branded and/or are they trustworthy?
Here is a link to a few links to some I've found:
http://m.ebay.com/itm/New-UNO-R3-ATmega328P-Development-Board-For-Arduino-Compatible-USB-Cable-DIY-/311418263595?nav=SEARCH
http://m.ebay.com/itm/NEW-UNO-R3-ATmega328P-CH340-Mini-USB-Board-for-Compatible-Arduino-WL-/161883302204?nav=SEARCH

The second link is not an exact UNO replica (different FTDI circuitry for USB -> potential driver issues). The first one seems an exact clone (from the PCB view), but obviously not officially branded, and probably using cheap components, all made and assembled in China. Personally I would not go for it.

@jfpoilpret I think it's worth a shot for 1/10 or the normal.arduino price

@J-Clarke I would not because it may appear to work for some time or for some fatures, but if some day it does not work for a new experiment, you will waste a lot of time finding out whether it is due to your program, your circuit or to this poor quality chinese clone (2nd link) or counterfeit (1st link). I can tell that, when working with reliable material, it is already difficult to "debug" your experiments, let alone when using crap...

@jfpoilpret Well the way I look it is like.your first car you buy a wreck because you have no idea howbto use it and you will probably overvoltage it or short the pins by accident

@jfpoilpret - the official Arduino Uno does not use an "FTDI" either.  FTDI is a brand, and perhaps semi-legitimately a casual reference to their flagship FT232 USB-serial chip.  But it is not a valid term for the USB-serial function in general especially in a case where the leading product - the Uno - doesn't even use that chip either.  You are right though that the ch340 can cause some headaches.

The CH340 needs unsigned drivers, which is a little harder to install in Windows 8/10 and OSX, but completely possible. Mine is running fine and can easily do 115k2 baud. I've also got one with FT232, but it appears that FT232 was a counterfeit, which initially bricked the chip. You would then have to reset the VID and PID of the chip, which honestly gave me more of a headache.

Caveat Emptor.
If it's not genuine you can never be sure quite what you are getting. You have to ask with some of then just how they can make them so cheap. Poor quality components is one way. Either counterfeit or reject components which may fail after a short time, or under certain conditions is a big risk.
There are different grades of board each with their own risks...

Genuine. High price, good reliability and quality. Good after sales support. Supports the Arduino cause.
Arduino clone. Genuine Arduino design made by a reputable third party. Almost as good as option 1 but doesn't support Arduino financially.
Arduino Based. A board created for a specific job that is based around genuine Arduino design. Support really only from the (often smaller) manufacturer. Quality varies.
Chinese clone. Low grade components made to original Arduino designs. Little or no support. Poor quality. Often with different USB interface that is unstable and low quality.
Counterfeit. Low quality components. Claims to be a genuine Arduino. Bad build quality.

Options 1-3 are ones I would consider buying. 4 and 5 I would stay well away from.

All the comments on these boards appear to be positive and reflect high quality. All the cheap boards on ebay have 4.5 or more stars. I think they are worth a punt

Be wary of high reviews these days, most of those are fake too. http://i.huffpost.com/gen/2575582/thumbs/o-WET-570.jpg?7

How many Arduinos do you need? If you are just getting one to learn on, for heaven's sake pay the extra fifteen bucks and support the cause.
If you are manufacturing something and need a few dozen boards, buy 50 Chinese ones and chuck the ones that don't work.

I live in Australia and arduino costs about 40-60 dollars

Actually I find many of the ebay shops very conscientious about their items, I have had a few experiences with defective items from ebay and must say that I've still not had a bad experience whether i get my money back or they resend the item, the downside is that it will take a new month for the replacement to get to me, money back usually goes within a few hours.

I wouldn't recommend using ebay-arduinos for "manufacturing". For fun little hobby projects it will be okay. @HansNeve, indeed, I had received a full refund because 2 out of 4 servo's were lost in transit. So I received 2 servo's and didn't have to pay for anything :) (and didn't have to send them back)

While, yes, caveat emptor, I have purchased a number of devices which are based on the Arduino open design. I have not yet had a problem.
Remember that, if you buy more expensive, prominently "Arduino" branded parts, from a third party, you also have no guarantee that they are quality controlled by Arduino. Even "genuine" electronics parts are usually manufactured in China, often in the same factories.
To answer your question, there are a number of ways the costs can be kept down:
Lack of unions, lack of labor laws, economies of scale, markup by the "official" companies, lack of development costs (remember, Arduino is open hardware, copying is allowed), cheap labor, tax, transport costs (there is some trickery in some countries, including Hong Kong, which makes shipping essentially free), shorter supply chain, cheaper components, smaller marketing budget.


text:
Regarding use of software serial two times
Can we configure two digital pins as serial pins using software serial library?

Kind of, yes - however you can't use them both at once. SoftwareSerial is blocking. That is, while one port is receiving or sending data the other port will be completely locked out so won't be able to receive anything. So it kind of breaks it in a nasty way.
Personally I never advocate the use of software serial unless there is absolutely no choice whatsoever, and that is something I have never found.
If you need more than one UART then pick a chip with more than one UART.


text:
How to measure water turbidity with arduino
I would like to measure water turbidity in the sea. The sensor does not need to measure it in an accurate way, I just need to know if water is clear or very turbided. I know that there could be used a light scatter but I do not know what kind of sensor should I use. Could anyone help how to measure turbidity?

http://uk.farnell.com/ams/tsl257-lf/sensor-light-voltage-converter/dp/1226886
is a good one according to http://forum.arduino.cc/index.php?topic=299993.0
But it might be easier to buy a COTS sensor, its a bit more expensive but much easier.  http://www.aliexpress.com/item/Turbidity-Testing-Sensor-Module-Suite/1903197650.html?spm=2114.01010208.3.17.OSVwdj&ws_ab_test=searchweb201556_9,searchweb201602_2_10017_9868_10005_10006_10034_10021_507_10022_10020_1000020_10018_10019,searchweb201603_8&btsid=6dbcca61-3e0a-4e34-9359-a6c26b268509
BTW for everyone else Turbidity is the amount of muck in the water, so it would be no good looking at the crystal clear waters off the UK coast :)

Thanks, do you think that there could be find any datasheet or part number of this chinesse COTS turbidity sensor?

You could try and ask the seller.  There are quite a few that sell similar units, ask them all and take the average of the responses as closest to the truth.  From the pictures and experience of similar looking sensors you seem to have both an analog and digital connections.  The digital could be in or out, in is usually the signal to make a reading, out is usually just condition sensed / not sensed.
The Sensor looks to be the same as a IR Tachograph sensor, but the receiver board is a bit more complex.  Generally the sellers are really helpful.

I used an array of cheap light dependent resistors hermetically sealed and used a torch. For dark water, it clearly shows a lower value than for cristal water. It is kind of a binary sensor, but I was proud of my basic invention!


text:
How can I power an Arduino Nano with a LiPo battery, preferably 3.7v
I am a newbie to Arduino, so please bear with me. I am trying to figure out how to power an Arduino Nano with a LiPo battery. I want to use a 3.7v if possible, as my project needs to be lightweight. There are two possibilities I know could work:
-Taking a USB to Mini-B USB, cutting off the normal USB end, and soldering a connector (based on the battery I use) to that end. I would then plug the Mini-B USB into the Nano, giving it power.
-Using the 5v and Ground pins.
I would prefer to use the USB cable solution, however the 5v/Ground or any other solution is perfectly usable.
Also, would 3.7v be enough to power the Nano, two Infrared LEDS (Launch and Receiver), and a 7-segment LED display. I also have a button.
                                                             Thanks, saddlepiggy!

In short: not reliably.  The Arduino Nano expects either a 5V regulated supply or a 6-20V unregulated supply (https://www.arduino.cc/en/Main/ArduinoBoardNano).  Even if you plugged it in and it worked initially, the battery voltage will decrease gradually as it discharges (LiPo cells can drop as low as ~3.2V), making it more and more unreliable.  You'd technically be overclocking the processor, since the Nano runs at 16 MHz and the datasheet for the microcontroller requires at least a 4.5V supply to run above 10 MHz.
A safer solution would be to use a 2S LiPo battery (~7.4V), which would be plenty to supply the regulated input pin (VIN).  On the other hand, if you're set on using a 3.7V LiPo, other Arduino boards (like certain versions of the Pro Mini) run at 3.3V.
As for your second question, 3.7V is plenty to power a few LEDs so long as they are connected in parallel (or to separate pins).  The only thing you need to be aware of is current draw--more current means shorter battery life.  For example, if your circuit draws 100 mA total from the battery, and your battery is specified at 500 mAh, you will get approximately (500 / 100) = 5 hours of battery life.

You could set the fuses so that it runs on the internal 8Mhz clock. I'm not sure if powering the chip with 7.4V would do any good, since it's rated 5.5V (unless you use the regulater input).

So just to clarify, if I use a 7.4v LiPo,then I can hack the USB cable right? Or if I don't do that, could I use an alternate battery, like a AA pack or something?

Late to the convo but quick comment in case anyone else reads this thread still. Arduino uses a linear regulator on Vin. In that case the “extra” voltage gets wasted. You’d get a much more efficient battery use by using a buck or boost circuit to provide it the correct 5V on the 5V pin (or usb) rather than feeding a 2S LiPo into Vin. It would work both ways but you’d get noticeably longer run time with a switching power converter.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Why does this method return an unprintable character, how do I convert it to display correctly?
Page 14 says that the method should return the value 'h17'
typedef struct  {
  uint8_t data;
  uint8_t timestamp;
  unsigned char crc;
} tData;

int main(void)
{
  unsigned char* tempData = "snap";

    for(;;)
    {
      tData payload;
      payload.crc = crc8(tempData,sizeof(tempData));
      UDR0 = payload.crc;
    }

    return 0;
}

Because “h17” is an unprintable character, namely ASCII ETB. The 'h' in “h17” stands for “hexadecimal”, like the 0x usually used in C.
You should convert the value to an ASCII number if you want to print it, using for example Serial.print(payload.crc, 16); or – if you are not using Arduino core – (s)printf().

Edit: here is an implementation of my comment “sprintf() into a
buffer and dump the buffer to UDR0 one byte at a time”:
#include <stdio.h>

void print_byte_in_hex(uint8_t byte)
{
    // Print the byte in ASCII into an internal buffer.
    char buffer[8];
    sprintf(buffer, "%02x\r\n", byte);

    // Send it one byte at a time through the USART.
    for (char * p = buffer; *p; p++) {
        loop_until_bit_is_set(UCSR0A, UDRE0);
        UDR0 = *p;
    }
}

I'm not using Arduino core in this instance. What is (s)? So something like: UDR0 = printf(payload.crc)

@SensationSama: I mean you either sprintf() into a buffer and dump the buffer to UDR0 one byte at a time, or you set up stdin to print through the serial port and then do something like printf("%02x\n", (unsigned int) payload.crc).

Okay great. Can you spoon feed me the buffer process a bit?

@SensationSama: done in the edit, but not tested.

Thanks, seems to work perfectly! One last follow-up question. If h17 is hexadecimal, and the decimal equivalent is 23, than why is my terminal printing 99?

@SensationSama: Hard to say without seeing the whole program. What does it print if you print_byte_in_hex(0x17)?

You're able to see all the code that is interacting here. That parameter results in a print of 17.


text:
Arduino controlling a heavy solenoid water valve
So after burning up a couple Arduinos, I'm running out of ideas...
I am trying to power both a Solenoid valve and the Arduino(nano) with the same 12V-2amp power supply. I've tried it with both a relay breakout board, and via transistor switching, and both are giving me sporadic behavior for the Solenoid.
Early failures came from realizing that the solenoid water value was actually a coil (duh), and thus needed some kind of diode placed over its connections, so I'm assuming the back voltage spike is what fried the first two boards.
At first I added a small diode that helped but wasn't enough, so I beefed it up to a 3 amp "rectifier diode" 200PIV, which stopped the board frying.
Here is a link to the solenoid water valve. Not much to go on I'm afraid. 12V 0.02-0.8Mpa.
The behavior that I'm seeing now, is that the solenoid will engage, but it won't disengage.
Do I need to add a Capacitor for the solenoid?  If so, any recommendations on sizing?

int relayPin = 2;

void setup()
{
  pinMode(relayPin, OUTPUT);
  Serial.begin(115200);
}

void loop()
{
  Serial.println("starting");
  digitalWrite(relayPin, HIGH);
  delay(2000);
  digitalWrite(relayPin, LOW);
  delay(2000);
}

The valve might require the water to be pressurized, to disengage properly. Using the water pressure instead of a sprint, like in regular solenoids.

Sorry, I did leave out that it's a "normally closed" solenoid.  I've tried direct powering with the 12v supply and it works fine that way.

Please double check your transistor pinout. The TIP3055 you name doesn't come in the TO-92 case you depict.

The red wire is connected to the Arduino or the power supply? Not very clear in the picture.

It's a prototyping board, so each vertical line (when laid horizontally) are all connected. So you'll see the the 12v power is provided to both the arduino and the solinoid

I have setup Arduino UNO and succeeded turning solenoid on when pot soil moisture dry, I was adding rain sensor when I mistakenly disvmcoonected the diode it fried my board, but atleast I had it working . I am using 24 volt normally closed solenoid , since I was monitoring over web I also had ethernet shield attached. And I was powering over ethernet using splitter and extracter.

The vin should only feed in 3.3 volt which you can get using stepdown buck converter , and use remains power to connect to solenoid. The transistor should be on the ground same as arduino nano the ground
The top became messy later

What I've discovered is that the step-down is the key. Because using the same 12v ground for both the arduino (directly) and the solenoid creates a feedback loop of some kind that keeps the transistor energized. The step-down buck your using to provide power to the arduino at 3.4V must include some kind of diode that is keeping the voltage from flowing backwards.

Try This Circuit...

I think you are overpowering Arduino Board.
Transistor Will not Carry heavy current for long duty period.
It easy to use Simple 5v relay board then you don't have to worry about Current limits and all...

If you review my diagram this is the exactly same setup I had already outlined, just using a different transistor. I'll try again with a TIP120.

The fact that the solenoid turns on but not off makes me think the Arduino might just not switch off the GPIO. This could happen if the current drawn by the solenoid is so high that the power supply voltage drops below the threshold needed for the Arduino, resulting in a reset.
The result would be that the Arduino repeatedly switches on the solenoid but is reset before it can switch it off again.
Try to flash the built in LED in the same main loop to verify that the loop is still alive.

authors: ธวัชชัย ชัยศลา


text:
Program nodeMCU Over the Air (OTA)
I have a Lolin NodeMCU V3 with a broken USB port: no power, no data.
It does show up on WIFI as AI-thinker_xxx, I can connect, but what can I do next?
Is there a way to program the NodeMCU Over the Air (OTA), or through some pins?
Description found here under V3

To clarify, if it shows up with that WiFi Access Point name, it is getting power. So the USB cable is working that much at least?

Also, if you can include a link to the exact hardware you have or a photo that would assist with figuring out what other pins would be helpful.

Nope, powered over shield.

If powering over Vin pin is working, you can use the board without USB.
ESP8266 is bootloaded over UART pins. These are pins marked RX or D9 and TX or D10 on the NodeMcu board. You can use USB to TTL serial adapter to bootload (flash) the esp8266. To put the esp in flashing mode hold the FLASH button and click the RST button and then release the FLASH button.
You can then upload a sketch with ArduinoOTA library and do following uploads over OTA. After USB upload of a sketch, reset the board with RST button before doing the first OTA upload.


text:
Can I measure velocity from an accelerometer? How accurately?
I've bought this module
Kootek GY-521 MPU-6050 MPU6050 Module 3 Axis analog gyro sensors+ 3 Axis Accelerometer Module
My project will involve affixing this to a moving object, moving at velocities varying from 0.1 to 1.0 meters per second.
From what I understand, this module will allow me to infer rotation and acceleration, will I be able to derive velocity?
How much accuracy can I expect?

http://www.chrobotics.com/library/accel-position-velocity

Attempting to integrate velocity from acceleration leads to integrating the error, ie, the error rapidly grows to the point where the result of the calculation is not so much "inaccurate" as "meaningless"

@ChrisStratton I'm pondering this as a replacement for my current prototype, which is a retractable string attached to a rotary encoder. Are you suggesting this is not feasible?

I need to be accurate within at least 0.05 meters per second

I don't think that will be possible. If my understanding of accelerometers is correct, they measure acceleration. Then you have a situation when the speed is constant. Acceleration = 0, according to Newton's laws. You would have to keep track of changes in acceleration then perform math to maintain the state. As Chris Stratton suggest, that will lead to keep integrating the error to the very likely situation of a meaningless value. Edit: however, I have never worked with an accelerometer before, so it can be possible at a certain extent.

@fabrosell This makes mathematical sense. Velocity is certainly the most important value for my project, so it sounds like this will be viable. You can post your response as an answer and I will accept it

The sensor in itself can't provide you the velocity. I have used it accelerometers in a couple of projects the easiest way to get the velocity is to constantly monitor acceleration changes and calculate velocity instantaneaously.
In order to do so follow these instruction. Pleas note that this is only 1 axis reading in actual case you will have to perform this for all three axis i.e. x,y and z.
I hope you are aware of the equation of motion (V = Vo + at)... The sensor will provide you value of acceleration at any given time. But acceleration can vary quite significantly during a huge time intervals so keep the time intervals 't' small. Lets say t = 10ms (depends on you). So calculate V after every 10ms intervale and this will give you current velocity at any given time. But what about Vo? As you know it is refered to as initial velocity so in the beginning it will be 0. Immediately after first reading when you are about to take second reading the Vo will change to the previous V calculated and hence forth.
This means Vo at any given interval is actually the V calculated in the previous interval.
I tried this method in my project when using accelerometer. hope it helps you as well.

Exactly. I forgot to add the Vo issue in my previous post.

How accurate was this? Did you verify or compare in some way?

And yes, I can correctly assume start velocity of V0 = 0m/s, however it is possible that the object might get moving from 0 a,d then stay at some velocity, or close to it, and not accelerate very much. Will this be a problem?

Well as long as your time delta's (intervals) are short enough that won't be a problem at all. Since this equation will provide you instantaneously velocity at any given time. If accelaration is zero at any given time that means velocity will be what it initially was.

@JamesWierzba As for how accurate. That totally depends on you accelarometer. I used a couple of them but they gave quite buggy values but they were the cheapest available. If you go for something solid then the results can me close to 100% precision.

@UsamaZafar do I need to increment t by 10ms every time? Or t will always be 10?

I work with Arduino-based autopilot modules, which usually use similar sensors in addition to GPS data to maintain a reasonable estimate of its position/velocity/acceleration.  If you were to add other sensors (i.e. a GPS) to your project, it might be worth looking into Extended Kalman Filters (https://github.com/simondlevy/TinyEKF), which are usually able to provide fairly accurate results.
If you're only using an accelerometer, EKF would probably be overkill, so you could look into other noise-reduction techniques.  For example, using a weighted average of the last two readings:
// alpha is value between 0 and 1
acceleration = alpha * readAccelerationSensor() + (1 - alpha) * lastSensorReading

Another strategy to filter out noise would be to take multiple sensor readings at each time step and use the median value to integrate for velocity.

The total distance moved is no more than 1-2 meters in +Z direction so gps is no good. Are you suggesting taking 3 readings at a single point in time? Why? Is the hardware that unpredictable?

Accelerometers in general are somewhat susceptible to noise from mechanical vibration of your device, so averaging the sensor readings would help to reduce the error from higher-frequency noise.  Whether this is an significant issue will depend on your application (how much your device vibrates during normal operation, and how much precision you need from your velocity measurement).

I don't think that will be possible. If my understanding of accelerometers is correct, they measure acceleration. Then you have a situation when the speed is constant. Acceleration = 0, according to Newton's laws.
You would have to keep track of changes in acceleration then perform math to maintain the state. As @Chris Stratton suggest, that will lead to keep integrating the error to the very likely situation of getting a meaningless value.
However, I have never worked with an accelerometer before, so it can be possible at a certain extent.
It would be great to hear from someone who actually tried this.

I think that calculating the instantaneous velocity as described by Usama is the correct method so long as you can deal with the cumulative error. I would also suggest that you provide regular recalibration to deal with that (like a return to home).
However, if you are trying to calculate velocity the best method would be to use a gyroscope, not an accelerometer.
Gyroscopes were (are?) how submarines navigate underwater. To measure acceleration with gyro sensors it is of course the rate of change of the velocity. V = Vo + at and d = Vo.t + (a.t^2)/2 are your two most important formulas.
Which you choose depends upon your application.  I would chose either based on whether my application is more likely to have constant velocity or frequently accelerating and decelerating. Maybe even have both...
I have not experimented with digital gyro sensors but note that there are a couple of Arduino shields available.

A gyro doesn't measure acceleration it measures rotation.

Rotation is by definition acceleration. A vector is speed plus direction. When you change either you are accelerating. So a gyro is measuring both speed and direction and giving you data in three dimensions.

Gyros measure angular velocity not lineair velocity. When you accelerate a giro in a straight line you don't get any output. One gyro will only give you angular velocity in one direction (axis).

We will have to agree to disagree. Yes you are right about angular velocity - but it is angular in relation to the gravity of the earth. So any movement will record a change. That includes a straight line that is tangent to the earth or moves around the circumference in an arc.  (I am not sure about how it works when moving in a straight line toward or away from the center of the earth’s mass.)

Clarification - Texas Instruments supply solid state gyros that work in three dimensions and the application notes indicate that they can measure movement in any axis so moving directly along the line of the gravitational force must be possible.

It seems that you confuse acceleration meters with gyro's. And you confuse the fundamental difference between lateral movement and rotation. Suppose a body with a gyro travels a full circle (i.e. around a circular trajectory). Then during the travel the gyro will tell you the angular velocity and, by integration, the amount of degrees it rotated from the start. At the end of the trip this will be 360 degrees. What the gyro will not tell you is the diameter of the circle.

@PimV okay. I am not one to hold back from admitting I was wrong. I was conflating this with using accelerometers with gyrostabilisation to keep the orientation of X,Y, and Z constant to you can track your location in a three dimensional space. The section on gyrostabilisation is where I got confused.  https://en.m.wikipedia.org/wiki/Inertial_navigation_system

Fair enough, case closed!

Use to compass + accelerometer
Use compass to eliminate g from the readings

Please expand upon your answer


text:
Removing Element From Array While Keeping Order
I'm building a wireless mechanical keyboard. There is an array of 6 elements that stores the keys pressed by the user (since 6 is the max number of keys you can send at once over Bluetooth). An example would be 02-05-03-00-00-00. Notice the "00" at the end, these are just "placeholders" and don't have a meaning other than to indicate that there are no more keys pressed. When the user releases key 05 for example, the array should become this 02-03-00-00-00-00. I don't know how to do this however, since you can't just remove and item from an array and there doesn't seem to be a polished option for lists in Arduino.
Does anyone have any idea for an algorithm that finds the 0's in an array, places them at the end of the array and keeps the order of the other elements?

You need to compact the vector: First search for the first non-zero element and then move all non-zero elements. It could look something like below:
void setup()
{
  Serial.begin(57600);
  while (!Serial);

  char vec[] = { 2, 5, 3, 0, 0, 1 };
  print(vec, sizeof(vec));

  compact(vec, sizeof(vec));
  print(vec, sizeof(vec));

  vec[1] = 0;
  print(vec, sizeof(vec));

  compact(vec, sizeof(vec));
  print(vec, sizeof(vec));
}

void loop()
{
}

void compact(char* vec, size_t len)
{
  int i = 0;
  for (; i < len && vec[i] != 0; i++);
  if (i == len) return;
  int j = i;
  for (; i < len; i++) {
    char c = vec[i];
    if (c != 0) {
      vec[j++] = c;
      vec[i] = 0;
    }
  }
}

void print(char* vec, size_t len)
{
  for (int i = 0; i < len; i++) {
    unsigned c = vec[i];
    if (c < 16) Serial.print(0);
    Serial.print(c, HEX);
    if (i + 1 < len) Serial.print('-');
  }
  Serial.println();
}

This give the following output:
02-05-03-00-00-01
02-05-03-01-00-00
02-00-03-01-00-00
02-03-01-00-00-00

Cheers!

Remove Zeros
void removeZeros(uint8_t array[], size_t length) {
// Sanity check.
if(array != nullptr && length > 0) {
    for(size_t i = 0; i < length; i++) {
      if(array[i] == 0) {
        for(size_t j = i + 1; j < length; j++){
          if(array[j] != 0) {
            array[i] = array[j];
            array[j] = 0;
            break;
          }
        }
      }
    }
  }
}

Usage:
uint8_t keyBuffer[] = { 2, 0, 3, 0, 4, 0 };
removeZeros(keyBuffer, sizeof(keyBuffer)/sizeof(keyBuffer[0]);

New value of keyBuffer: { 2, 3, 4, 0, 0, 0 }

Remove a single indexed value
void removeIndex(uint8_t array[], size_t length, size_t index){
  // Sanity check.
  if(array != nullptr && length > 0) {
    for(size_t i = index; i < (length - 1); i++){
      array[i] = array[i + 1];
    }
    array[length-1] = 0;
  }
}

Usage:
uint8_t keyBuffer[] = { 2, 5, 3, 0, 0, 0 };
removeZeros(keyBuffer, sizeof(keyBuffer)/sizeof(keyBuffer[0], 1);

New value of keyBuffer: { 2, 3, 0, 0, 0, 0 }


text:
Send newline through serial monitor
I know I can send a newline using the option in the bottom right:

But why doesnt it work to use the option 'No line ending', and send a '\n' or '\r\n' after the text using the arduino serial monitor?

The backslash escape encoding for special characters is a feature of double quotes in some programming languages, shells, and other parsers.  It is not normally a feature of live text input - an "end user" human typing a backslash is assumed to mean it literally.
"Live" input of a carriage return or newline is more traditionally done with the return/enter key, or with the corresponding control codes - CTRL-J for newline and/or CTRL-M for return.  I don't know that the Arduino IDE's Serial Monitor supports either of these, at least once you select "no line ending"


text:
How do I connect a vibration sensor/switch to a breadboard?
I have the following vibration sensor:

It has one short/firm-er terminal and one long/flimsy terminal.  Now the shorter terminal slides easily into my breadboard but the flimsy one clearly does not.  A few related questions:
1) How do I go about connecting this to my breadboard (simply plugging it in doesn't work)?  Do I have to solder a wire onto the flimsy end?
2) Why is this switch manufactured this way (with a flimsy end)?
3) Is it right to assume that the longer end is positive (+) and the shorter end is negative (-)?
Thanks!

It appears from this information source:
http://www.electrodragon.com/product/vibration-switch-sensor-sw-18020p/
that the sensor is an electrical contact on the firmer side surrounded by a very sensitive spring within the enclosure. The coil spring is by design made of a smaller diameter wire to provide sensitivity to movement. Rather than manufacture a translation to a heavier piece of material, the thinner lead is brought out of the enclosure.
I suspect that it will not work on your breadboard, due to the flimsy end being too small to make solid contact within the breadboard. You could resolve that aspect by soldering on a heavier segment.
Because it is designed as a simple switch, there is no plus or minus.

Thanks!  That worked.  I soldered the flimsy end, plugged everything into a breadboard and now I'm getting a whole bunch of readouts.  I guess now I'm trying to figure out how to set certain thresholds but the numbers are all over the place.

From the information sheet, it appears that the spring will continue to contact the center post with a frequency based on the magnitude of the vibration. If one considers this to be a push button switch, it has a serious problem with debounce. Perhaps adding a debounce segment of code to your program will help?


text:
Arduino UNO doesn't produce expected square waveform
I want to produce quick square waveform for testing purposes. If I will use this code:
void setup()
{
 pinMode(2, OUTPUT);
}

void loop()
{
 bitSet(PORTD, 2);
 bitClear(PORTD, 2);
}

I will get expected pulses but I also will get these 6.25 us dips in waveform roughly every 1 ms.
I use latest Arduino 1.6.9 environment.
Whole loop cycle take 1 us which mean 16 instructions (62.5 ns per instruction). So I will get 125 ns high and rest of the time low signal.
Any idea what I'm doing wrong?
Same results if I use asm sbi and sci instead of macros bitSet/bitClear.
Thank you!

/*
So after yours advices and little bit further searching I came up with solution to produce clean square waveform. It make 2.66 Mhz and it's probably fastest what you can get:
void setup()
{
 pinMode(2, OUTPUT);
 noInterrupts();
}

void loop()
{
 while(true)
 {
 bitSet(PORTD, 2);
 bitClear(PORTD, 2);
 }
}

On the Uno, the Timer 0 overflow interrupt kicks in every 2014 µs. This is probably the glitch you are seeing. If you want to avoid it, do not use Arduino core, just plain avr-libc.

Or disable interrupts.

“Whole loop cycle take 1 us which mean 16 instructions”. There are actually only 6 instructions. Two of them take 4 cycles each (call and ret), the others take 2 cycles each (sbi, cbi, sbiw and breq).

Yes. I should have write "cycles" instead instructions.

The fastest you can get is 8 MHz: take the “Use a hardware timer” code I posted and change the OCR2x registers to OCR2A = 1; OCR2B = 0;.

@EdgarBonet Wow! Awesome! Your knowledge about Arduino amazes me! Thank you very much!

As I explained in my comment, the reason for this glitch is the Timer 0
overflow interrupt kicking in every 1024 µs. This interrupt is used
by the Arduino core library for timekeeping. It is the basis of
millis(), micros() and delay(). The interrupt is enabled by the
init() function in
wiring.c.
There are several approaches to avoid that:
Avoid the Arduino core initialization
This may be overkill, but since it seems you are already familiar with
directly accessing the IO ports of the ATmega chip, it may well suit
you. You can use the Arduino IDE without the Arduino core initialization
simply by defining your own main():
#include <util/delay.h>

int main(void)
{
    DDRD |= _BV(PD2);        // PD2 as output
    for (;;) {
        PORTD |= _BV(PD2);   // PD2 high
        PORTD &= ~_BV(PD2);  // PD2 low
        _delay_us(0.625);    // 10 CPU cycles, loop time = 16 cycles
    }
}

Notice the extra delay: without it, the loop would complete in 6 CPU
cycles (2 per port access, 2 more to loop back). Not doing the Arduino
core initialization means you have no timekeeping and no analogRead()
or analogWrite(). Other Arduino functions should work normally but
some, like Serial.begin() will bring their own interrupts.
Disable interrupts
As suggested by Majenko, this may be the simplest way to have a steady
waveform:
void setup()
{
    pinMode(2, OUTPUT);
    noInterrupts();
}

void loop()
{
    PORTD |= _BV(PD2);   // PD2 high
    PORTD &= ~_BV(PD2);  // PD2 low
}

Without interrupts, you have no timekeeping, no serial communications
and, obviously, no attachInterrupt(). Most other Arduino functions
should work.
Use a hardware timer
This allows you to generate the signal without relying on the CPU. You
can keep interrupts enabled and do other work in the program while the
waveform goes undisturbed. The simplest way to generate such a waveform
is with analogWrite(). The resulting frequency is quite low though,
like 0.5 to 1 kHz. If you want 1 MHz, you will have to
configure the timer the hard way. For example:
void setup()
{
    DDRD |= _BV(PD3);     // OC2B = PD3 as output
    OCR2A = 15;           // period = 16 clock cycles
    OCR2B = 1;            // high during 2 clock cycles
    TCCR2A = _BV(COM2B1)  // non-inverting PWM
           | _BV(WGM20)   // fast PWM, TOP = OCR2A
           | _BV(WGM21);  // ditto
    TCCR2B = _BV(WGM22)   // ditto
           | _BV(CS20);   // clock at f_CPU
}

void loop() { }

The output is on pin PD3 = digital 3. This configuration will disable
analogWrite() on pins 3 (PD3) and 11 (PB3).

What piece of Arduino starts this timer / implements it's interrupt (you should kill it at it's roots? So you can still use other interrupts)? And is there an easy way to see which pieces of code depend on the timed interrupt of Arduino?

@Paul: It's all in the wiring.c file I already linked to. The interrupt service routine only updates three variables: timer0_millis, timer0_fract and timer0_overflow_count. These are only used inside wring.c. You can see what depends on the interrupt by searching for these variables through the file: only millis() and micros(). But then delay() depends on micros(), Stream on millis(), and some USB stuff (not on the Uno) on delay().

Cool, so I could disable this interrupt and still use libraries that use interrupts (such as servo/softserial). Or well, I would have to check if they rely on millis() or micros().

@Paul: That's correct, but any enabled interrupt would cause the kind of glitch seen here.

So I added noInterrupts(); in my code and now the waveform is perfect! Thank you very much @Edgar Bonet! And I will try other methods too. There is still so much to learn. I am familiar with Arduino timer but I thought it doesn't affect running program. BTW You all probably know it but these microcontrollers are so cool  :D haha

I want to produce quick square waveform for testing purposes.
Whole loop cycle take 1 us which mean 16 instructions (62.5 ns per instruction). So I will get 125 ns high and rest of the time low signal.
  Any idea what I'm doing wrong?

You are assuming that what goes on outside loop() and the call to loop() takes no time at all.
This is what the Arduino core main() looks like.
int main(void)
{
    init();

    initVariant();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}

There is both the call to loop(), if-branch, and for-branch. This all adds up. On top of this there are a number of Interrupt Service Routines (ISR) such as for the Timer which is used for the micros() and millis() count. These will interleave periodically (as you have observed).
Now the question is how to fix this and I think @Edgar Bonet has done an excellent job with that.
Cheers!

If you just want a rough square wave to test and you don't care about the frequency then try this:
void setup()
{
   pinMode(2, OUTPUT);
}

void loop()
{
   digitalWrite(2, true);
   delay(2);
   digitalWrite(2, false);
   delay(2);
}

If you don't care about the frequency, analogWrite(3, 128); is simpler.

@sa_leinad: I care about frequency so I used bitSet/bitClear to make it quicker. Now I have clean 1 Mhz waveform (thanks to Edgar) which I will never achieve with standard digitalWrite.

Could you please edit your question to reflect this information.


text:
Arduino project - will this fit together?
I'm about to order parts for my project and I'd like to avoid some rookie mistake I might've missed. I'll be using Arduino chip and a wifi module to host a very simple webpage and a battery to make this all portable. I've decided to use Arduino Mini Pro 8MHz because of 3.3V input voltage, same as ESP8266, also FT232RL to program the board and TPS73601 for my battery. This is where I have some doubts, the battery I've picked is Li-Ion from my old Samsung Galaxy S AFAIK when charged it supplies ~4.2V and nearly discharged ~2.7V so the regulator should work (?). Is using Li-Ion in any way different from regular AA or just +/- because I see 3 pins on the back of it? Except for charging of course I'll be using the phone for that. Thanks in advance for any suggestions.

have you considered programming the esp8266 directly? It has a few GPIO pins and can host small webpages.

http://randomnerdtutorials.com/esp8266-web-server/

I had not known that, but I'll be using a couple of analog sensors in my project, did not include them here because they are pretty straight forward. I assume GPIO on ESP8266 are digital? If so then I'll have to stick with Arduino chip anyway.

From what you've provided everything seems to be compatible.
Concerning the battery, a quick look at the Arduino website shows:

Input Voltage 3.35 -12 V (3.3V model)

Meaning the regulator will work as long as the battery provides voltage above 3.35 but since your battery's voltage drops as it gets depleted you might not get the battery life you'd expect :/. In other words: it'll work initially  until the voltage drops below 3.35V and then you would have to recharge it.

Is using Li-Ion in any way different from regular AA

Yes and No.
No : both provide a stable DC source and both can be used in similar applications.
Yes: Li-Ion batteries can be recharged and have a longer life-span, and most importantly, Li-Ion batteries don't have a sharp voltage drop as they get depleted, unlike regular AA batteries. Which is a bonus for this project ( i guess :p )

I see 3 pins on the back of it

There are only 2 pins that actually provide the power from the battery while the third is usually used to monitor temperature or battery life remaining.So you can use this battery by only connecting the power providing pins (usually indicated by + and - ) and safely ignore the third.
Gd Luck!


text:
Join Serial Data Seperated by Newlines?
I have two Arduinos connected through Bluetooth. One sends a string of data similar to 506:507:1\r\n. The data can vary similar to 0:1000:0\r\n. I already have functions to break that string down into three variables. I send it from one Arduino over Bluetooth and the second Arduino receives it through Serial. The only problem is that the second Arduino receives this:
5
0
6
:
5
0
7
:
1
"\n"

At the end it adds a space at the end ("\n") How can I parse this data back into a string similar to 506:507:1\r\n that can still vary in length?

Read this: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

I don't see what the problem is?
Though, you do seem to miss the \r?
And I don't see the space at the end? You can easily make it a string by adding the characters to the string, until you receive your end character \n?
Maybe https://www.arduino.cc/en/Serial/ReadStringUntil is an easy to use, "all in one" solution for you.

Simply reverse the steps you took on the sending side.

Create a char array of sufficient size as well as an index variable to keep track of your position within the array. An Arduino String may be more convenient, though they can cause a lot of problems.
In a loop, use available() to wait for incoming chars and add them to the array you've created, using your index variable.
Keep going in the loop, while checking for that unique character (\n, perhaps) that signals the end of a packet. Add this last byte to the array and then terminate the string with null or \0.

If you want to re-use the array for another packet, simply set the index variable to 0 and continue.


text:
No sketches will upload to Arduino Uno board; says "access denied"
I'm using an Arduino Uno board with an HP computer running Windows 10 and IDE version 1.6.8. Arduino was working fine for me until a few days ago, when (and I suspect this is the root of the problem) I accidentally tried to upload software with something connected to the RX and TX pins on the board. Now I continually get the error message below:

avrdude: ser_open(): can't open device "\.\COM2": Access is denied.

The only other thing that changed is I disconnected a bluetooth dongle (Kinivo BTD-400 Bluetooth 4.0 USB Adapter for Windows) without uninstalling any software, so I suspect that software may be searching for open COM ports and disrupting the Arduino upload.
I've tried everything I could find about troubleshooting online, including that "did I brick my arduino" post elsewhere on this forum, and nothing has worked or even changed the problem - please help! I believe I've narrowed down the problem to my computer scanning open COM ports, but I can't find any reliable way to make sure that doesn't happen.
Thanks

Have you tried powering down your PC and turning the power-plug in the socket the other way around? This often fixes this issue. (Given you're using AC power)

It sounds like Windows thinks that port is in use and isn't letting the ArduinoIDE access it. If it's the same port your dongle had been using, try plugging the dongle back in, then dismounting it before you remove it. Hopefully that will clear the port for other uses.


text:
Send Newline / Carriage return with python
With the Serial Monitor I have the Newline option:

How can I send the same using python?
I tried:

30\r\n
30\r
30\n

import serial

ser = serial.Serial('COM3', 115200)

while True:
    numIn = input("enter delay value: ")
    ser.write(numIn.encode('ascii'))

You tried them and they didnt work? ser.write((numIn + '\r').encode())? How are you checking this?

Thanks, this (numIn + '\r\n') works. Typing \r\n does not for some reason.


text:
serial communication dead slow after a while
I'm workin on a node for blender to control an arduino. I notice it goes really slow after a while so I isolated the problem.
It is good in maintaining 60 frames a second, then after around 40 seconds (pretty exact), it drops to a pretty exact 1 fps for some reason.
What could be going on?
import serial
import time

ser = serial.Serial('COM3', 115200)

c = 0

while True:
    c+=1
    print("ok ", c)
    numIn = "100n"
    ser.write(numIn.encode('ascii'))
    time.sleep(1./60)

arduino code:
// special thx to  Nick Gammon
const unsigned int MAX_INPUT = 50;

unsigned long delay_time = 300;
unsigned long last_toggle_time = 0;
int current_state = LOW;

void setup () {
  Serial.begin (115200);
  pinMode(12, OUTPUT);

}

void process_data (const char * data) {
  Serial.println (data);
  delay_time = atoi(data);
}

void processIncomingByte (const byte inByte) {
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  switch (inByte) {

    case 'n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte
      process_data (input_line);
      input_pos = 0;
      break;

    case 'r':
      break;

    default:
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

  }
}

void loop() {

  while (Serial.available () > 0) {
    processIncomingByte (Serial.read ());
  }

  unsigned long m  = millis();

  if (m > last_toggle_time + delay_time) {
      current_state = current_state == HIGH ? LOW : HIGH;
      digitalWrite(12, current_state);
      last_toggle_time = m;
  }

}

Hint: Check "if (m > last_toggle_time + delay_time)" and what happens when millis() as int wraps?

I changed it to unsigned long now and it's still the case.

Also, the blinking is not the problem, that keeps going well. It's the serial communication that slows down.

What happens if you remove the Serial.print() from process_data()? What does your Python script do with serial input?

Cool, if I remove the print then the problem is gone. However, eventually I want python to read the input. Now python hangs on ser.readLine(). Maybe a new topic for the hanging?

Now we need an explanation not dive directly into the next issue :) What was the problem, really? The Arduino prints. The host (Python) script does not read and internal USB/USART buffers are filled. And what happens on the Arduino side when the Serial output buffer is filled? Check the code - it is open-source :)

BW: Be a good stackexchange user and write an answer and mark this question as answered.

I guess it goes in a second delay :)

@MikaelPatel "Serial" output data unclaimed by the host could only potentially be a cause for slowdown in the case for a Leonardo board or something else where the USB is implemented directly in the application processor, and even there it is a bit uncertain.  It is definitely not the case for an Uno or something where the application processor has a UART connection to a USB converter, as in such case the UART data is blindly transmitted, regardless if the receiver is able to handle it or not.

Please state which Arduino you are using. There is some confusion by responders as to whether outgoing communications would block if you fill up the buffer.

I just want to point out that you are using n as a delimiter in a rather unusual way. In my code it was \n and \r (newline and carriage return). When you do Serial.println (data); you are adding two more bytes (println adds a carriage-return and linefeed) so you are printing 6 bytes for every four you receive. It doesn't totally surprise me that something fills up after 40 seconds, however at 115200 baud that shouldn't really be an issue for 60 x 6 bytes.

Bit bang it with a delay loop before the next bit gets sent.
Delay loop variable will have to be tested to not be too quick. Sync it with baud rate. I developed a product which was trademarked as "Bit Banger" which was a serial I/O controller before you were mostly born back in 1997.
Then again it may help that My 1st real job was peripheral controller tech for a 16 bit computer company in the early 70's. Intel had jusr released the 4004 4 bit slicer. By 74 they came out with tge 8080.
Harry

If you print from arduino to serial and you don't read it then the buffer gets full. Causing it to go in a second delay. So make sure you read as well when you send data over.
A short sleep is required between the sleep and the read for some reason. Else it hangs.
import serial
from time import sleep

ser = serial.Serial('COM3', 115200)
sleep(1)

c = 0

while True:
    c+=1
    print("ok ", c)
    numIn = "100"
    ser.write((numIn + '\r\n').encode())
    sleep(1./120)

    inp = ser.readline()
    print(inp.decode("utf-8"))
    sleep(1./120)

The theory behind this answer is quite dubious, and if you have a conventional Uno type Arduino or something with a distinct USB-serial converter, impossible.


text:
I²C only works when I short-circuit my Arduino
I'm trying to connect an Arduino Nano with a Raspberry Pi 3 via I²C.
This is the small test-program I found and used for I²C.
#include <Arduino.h>
#include <Wire.h>

void setup() {
  Wire.begin(4);                // join i2c bus with address #8
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600);           // start serial for output
}

void loop() {
  delay(100);
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
  while (1 < Wire.available()) { // loop through all but the last
    char c = Wire.read(); // receive byte as a character
    Serial.print(c);         // print the character
  }
  int x = Wire.read();    // receive byte as an integer
  Serial.println(x);         // print the integer
}

After compiling and uploading, I ssh-ed into my Pi and executed sudo i2cdetect -y 1 which prints an empty I²C table.
Here are images of how I connected the two devices, as far as I know the connection itself is okay. I also tested the cables with a multimeter.

Now the strange thing is, when I short-circuit my Arduino for a brief moment between GND and VIN I²C works, but Serial via USB with my PC stops working. Also the chip gets very hot and stays hot even though it isn't short-circuited anymore.
Any ideas what I'm doing wrong? I don't think the Arduinos are broken, since I tested it with 2 different ones. (while testing I accidentally short-circuited one and it worked)
EDIT: I tested I²C between the two Arduinos and it works flawlessly, but still doesn't want to work with my Pi. :(

Any ideas what I'm doing wrong?

Apart from deliberately shorting +5V to ground? Sheesh!

Get, or make, a level-shifter. You can't pump 5V from the Nano to the Pi and expect things to work. Example schematic:

In this example the low voltage (3.3V) side is marked LV, and the high voltage (5V) side is marked HV.

You can use a level shifter with I²C but you don't need one. The Pi has pullup to 3.3V. Provided there are no other pullup it works. I routinely do this.

The important phrase there is "Provided there are no other pullup".
Wire.begin() enables the pull-ups. So make sure that on the Nano side you disable them again:
  Wire.begin (4);
  // disable internal pullups for twi.
  digitalWrite(SDA, LOW);
  digitalWrite(SCL, LOW);

To be fair, I didn't do it intentionally the first time, that was an accident. Then I had to verify my findings. :)
Also does it have to be a 2N7000?

No it doesn't. Many logic-level N-channel enhancement MOSFETs should do. Read Bi-directional level shifter for I²C-bus and other systems - PDF. And you can buy them on boards, eg. 4-channel I2C-safe Bi-directional Logic Level Converter - BSS138

@Dodekeract You can use a level shifter with I²C but you don't need one. The Pi has pullup to 3.3V. Provided there are no other pullup it works. I routinely do this.

@Milliways what am I doing wrong then? I attached the cables on my Pi and on my Arduino. Didn't add any resistors.

Edited answer to incorporate this suggestion.

On the Atmega328P running at 5V Vcc, a HIGH value is 3V and above. 3.3V is only marginally above this. Plus with weak pull-ups it may take a while to reach that. You may be better off adding 4.7k resistor pull-ups to both SDA and SCL to 3.3V (not 5V).

@Dodekeract Frankly I can't tell from your images exactly what you have connected. See http://blog.oscarliang.net/raspberry-pi-arduino-connected-i2c/ NOTE the hardware is still OK, but Pi software is no longer relevent.

@NickGammon The Pi has 1.8kΩ pullups on board. I was unaware the Wire.begin() enables pullups. Is this documented? Even if these are enabled the effect to the 1.8kΩ to 3.3V would minimise any overvoltage. It is not widely discussed but the Pi (like most IC) would be tolerant of overvoltage which is less than a diode forward drop. A diode clamp to 3.3V is a standard engineering solution to protecting digital inputs.

It's not documented here.

There is not enough information in your question to know for sure, but remember that the rpi is three volt and the arduino is five volt. Given the heat you are seeing you have something miswired.

The heat only starts when I intentionally for a short moment connect GND to VIN. Before I do that once I²C doesn't work, afterwards it does, but serial stops working. Also: What kind of information do you need? I can try to get it.

@Dodekeract - As hildred says, the Nano is 5V. You would be better off using an Arduino Micro Pro 3V, en lieu of a Nano.

Yes, but a Nano is what he has to hand. A couple of transistors will be cheaper than a new Arduino. However you can never have too many Arduinos. :)


text:
How to load Atmega328p 8mhz board using board manager
I need to load the Atmega328p 8kHz board definition using the board manager and can not find a way.  Any help will be appreciated.

8Khz or 8Mhz? AFAIK there is no 8Khz built-in crystal/osscilator.

Your question doesent make much sense, Are you using a 8MHz crystal or do you want to use the internal 8MHz rc oscillator?

And.. do you already have the board definition or not?

Assuming that you have a 3.3V Atmega328P and are using an external 8MHz occilator:
In the Arduino IDE click on Tools.
Scroll down until you see an option starting with the word Board:
Select the option called Arduino Pro or Pro Mini
Click the Tools menu once again.
This time select the option starting with Processor:
Select the Atmega328P (3.3V, 8MHz)
Done!
Alternatively you can edit the boards.txt file located somewhere similar to C:\Program Files (x86)\Arduino\hardware\arduino\avr
Fuse bits can be calculated using one of these online tools:

http://www.engbedded.com/fusecalc/
http://eleccelerator.com/fusecalc/

Assuming that you have a 3.3V Atmega328P and are using an external 8MHz occilator: If this is not the case then please amend your question with the specifics and I will edit my answer to suit.

The 3.3V part shouldn't matter.

Was the answer helpful? If so, please accept it by clicking on the "tick" icon next to the answer, and also possibly upvote it. This indicates to other users that you found the answer useful, and it also stops Stack Exchange from periodically "bumping" your question in the hope of getting an accepted answer. Thanks for your understanding and cooperation!


text:
radio wave generation using arduino

const byte ANTENNA = 9;

void setup()
  {
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaler
  OCR1A =  9;       // compare A register value to 10 (zero relative)
  }  // end of setup

void loop()
  {
  pinMode (ANTENNA, OUTPUT);
  delay (500);
  pinMode (ANTENNA, INPUT);
  delay (300);
  }  // end of loop

It is just toggling the mode of the pin, so how it is related to radio wave generation?

This looks incredibly like the post on my page: Turn your Arduino into an AM radio transmitter!
As the page mentions:

The 16 MHz clock is divided by 10 (that is, 1.6 MHz) and that is used to toggle pin 9 at that rate, giving a frequency of 800 KHz, since one toggle turns the output on, and second toggle turns it off.

These are the important lines:
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaler
  OCR1A =  9;       // compare A register value to 10 (zero relative)

Timer 1 is set up to run at 800 kHz. That is a radio frequency. The toggling code just turns the output on or off as a simple form of "keying".


text:
Did I fry a Sainsmart 1602LCD (not shield, just LCD), HD44780 compatible
Each new circuit I build, I seem to make every possible mistake, including inverting 5V and ground.
I did that precise mistake on this 2x16 Sainsmart LCD. The backlight definitely works, but is the only thing I seem to be able to make work. Do you believe I fried the screen, or do they maybe have a diode to protect from erroneous cabling, and my mistake is another one?
EDIT :
I found this somewhere, on a board that might be the one driving this LCD screen or not :
Operating Voltage VDD -0.3 to +7.0 V
Driver Supply Voltage VLCD VDD - 10 to VDD + 0.3
So I mistakenly put 5V in VLCD, and 0V in VDD, which makes VLCD 5V and not 0.3V above VDD, would you suppose I fried it?
Thanks for your input :)

Make sure you set the contrast using a potentiometer. Not seeing anything on the display, doesn't mean it's not working. If you only connect Vcc, GND and the Contrast pin, and you turned the pot to the correct position, you should see the first line filled with solid block, and the second line should be clear.

These things are reslient, because, according to the datasheet I was 4.7V outside specs, and your trick did it. I suppose if I saw the matrix of dots, it means it can print dots, and if it can print dots, it ain't fried. Thanks. Now I'll have five extras, but that'll just mean five projects who could do without will do with a LCD :D

I just succesfully did the hello world, thanks to you. If you'd only make an answer rather than a comment, I'd be able to select it. In any which case, thank you.

For me, it's extremely hard to tell if you did or did not fry a device.
Even if you have the device right in front of you, it's often hard to tell.
You've got two options:
Attempt to diagnose it
First you should try to run example code and follow the "instructions". I believe this product is relatively well documented (/libraried?) and shouldn't be all too hard to set up.
If this isn't working, it's likely the device is dead (given the situation). You could go on and fiddle around with it for hours, which might not be worth the effort.
Buy a new one
This will cost you some money. But if you get the new one working, you can test the same code on your old one.
Tips

First connect the wires, check the wiring and AFTER THAT connect the power. (Especially take care on GND/VCC wiring.)
Use black wires for GND/ground and red wires for VCC/5V.(It'll be easier to manage/spot)
Check the devices datasheets (which pins, what maximal voltage)
Try to use female connectors as power-output. (They don't short everything they touch)
Try to use irreversible connectors.
Don't have loose leads dangling around.
Put a casing/backplate on your Arduino (and/or avoid placing it on metal)
Keep your desk clean, bits of solder, wire, leads or screws may cause shorts between pins.

It may also be worth checking if only the "LCD driver" isn't working.

I ordered some LCDs (5 for 7 euros, crazy); they will probably take some time to come here, I'll answer when they do and I test a hello world on them.

Neat! Do they come with an "LCD driver"? Or well, it would be possible to drive them directly, but that would take a little more pins.

No, no driver, six pins (if you only write, seven if you read)


text:
"missing filename" compilation Error
I've recently got back to my Uno. I tried compiling my program and got the following error:
Arduino: 1.6.6 (Windows 8.1), Board: "Arduino/Genuino Uno"

avr-g++: error: missing filename after '-o'

exit status 1
Error compiling.

This happens on any of the programs I've tried to compile/upload.
I've searched around on Google but I have gotten no definite answers and how to fix this or what has caused this? Does anyone have an idea on what I could do?

I had same problem. You should download Arduino IDE 1.6.8
https://www.arduino.cc/en/Main/Software


text:
Random numbers being printed back after entering data
I am currently working with an Arduino Micro / Linduino and making a program based on a lot of switch statements to execute certain functions that will be passed to a microprocessor (LT2974) on a board serially. For the most part, all of the functions I have work, except there is one that I am trying to determine if it is my program that is causing issues, or the Linear Tech libraries that are provided. Upon research, I did discover something strange in my code that I cannot explain.
Here is a quick snippet of my code:
unsigned long serialdata;
int inbyte;

long getSerial()
{
  serialdata = 0;
  while (inbyte != '/')
  {
    inbyte = Serial.read();
    if (inbyte > 0 && inbyte != '/')
    {
      serialdata = serialdata * 10 + inbyte - '0';
      Serial.print(serialdata);
      Serial.print("test \n");
    }
  }
  inbyte = 0;
  return serialdata;
}

void loop()
{
  getSerial();
  // Switch statement represents Slot choices
  switch (serialdata)
  {

    case 1:
      {
        commands(Slot1);
        break;
      }
    case 2:
      {
        commands(Slot2);
        break;
      }
    case 3:
      {
        commands(Slot3);
        break;
      }
    case 4:
      {
        commands(Slot4);
        break;
      }
  }
}

I have left out the following switch statements that are found in the commands function as they are not where the issue lies.
For some reason, when I pass data through to the Arduino, and then go to reprint it out with my Serial.print command in getSerial(), there is an additional number printing, and I believe the issue to lie here.
So, for example, if I type "/1/" (the slashes were used to pass multiple variables as shown in the function, but I'm only passing one for now), the Arduino reponds with:
1test
4294967268test

here is "/2/"
2test
4294967258test

and here is passing multiple variables with "/2/9/"
2test
9test
4294967258test

All of the values I just showed you do not correspond to any of my switch statements implemented, and so no actual data is being returned besides the print command from getSerial(). So can anyone explain what is going on here?
EDIT: I added the data types of serialdata and inbyte to the top of the post.

4294967268 is (unsigned long)(20 - '0').

The problem is that you are blindly reading serial data without first looking to see if there is actually any serial data available to read.
If there is no data there Serial.read() will return -1.  Since you have only provided a snippet of your program I can't say what data type inbyte is, but my guess is it's some form of unsigned 32-bit value, since -1 mapped into an unsigned 32-bit value is 4294967295.
You need to be checking the presence of data, and only reading when you should read, and also looking for the end of your data sequence (add some terminating character, like a line feed) to know when to stop looking for and reading characters.

I edited my post. Did you mean to say that you believe serialdata is a 32 bit unsigned int? because that is what I am printing and that would make sense. Also, I am reading the data and storing it to inbyte, but shouldn't it not go through the Serial.print part since the last character i am entering is '/' and I told it to ignore that?

Ah yes, serialdata of course I meant.

So it seems the issue is that my getSerial() function reads the data, stores it to inbyte, and doesn't recognize the data as <0 or '/' so it is going into the loop and printing that value to serialdata, which looks strange but is actually correct? So the next question is why is it going into the loop again then?


text:
Which tft works on both Arduino Uno and Raspberry pi
Ideally I'd like a 2.8 inch and it to be touch screen.
But most of all I'd rather it work on both boards without much hassle.

Uno works at 5V and Pi at 3.3V, keep that in mind. A display with SPI, I2C or uart is likely to work on both, given the right circuitry for the difference in voltage.

Well any display can work on both of the boards if you can adjust the voltage levels right there is a display which was made for old Nokia phones and it is called nokia-5110-3310 and  is dirt cheap display and it can be used with both Arduino or raspberry pi or any other board which support the protocol here is a link for quick reference.
Adafruit link to the library

adafruit has a resistive touch screen which is 2.8" and works on most boards. Its 30 dollars and works well. It has instructions and all and libraries which you can use. Plug it into a breadboard, connect the jumpers and you're all set.
https://www.adafruit.com/product/1770
on the other hand, Elegoo has made a very similar product, which can also be used on most boards if you plug it into a breadboard, but it is specially designed for the UNO. You can plug it straight into the UNO board, without the need of breadboards. This comes with a instructional DVD and is only 12 dollars on Amazon. It is also a resistive screen and basically the same product.
https://www.amazon.com/gp/product/B01EUVJYME/ref=oh_aui_detailpage_o04_s01?ie=UTF8&psc=1
Good luck!

authors: 杏悦2娱乐代理--平台总代


text:
Why does this code show me a lot of space?
I want to make a 4hz reading of GSR and temperature, in the following format for every second:
697,20.8744
696,20.86521
695,20.8653
699,20.8777

The print, in python, would be print(GSR+","+Temp)
The tries in C are giving problem, here's my actual code:
#include <OneWire.h>

const int GSR=A0;
int threshold=0;
int sensorValue;
unsigned long startTime = 0;
#define MEASURE_PERIOD 250
OneWire  ds(3);

void setup(){
  long sum=0;
  Serial.begin(115200);

  for(int i=0;i<500;i++)
  {
  sensorValue=analogRead(GSR);
  sum += sensorValue;
  delay(5);
  }
  threshold = sum/500;
  }

void loop()
{
  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float celsius;
    if((millis() - startTime) >= MEASURE_PERIOD)
    {
        startTime += MEASURE_PERIOD;
        // Do your job, such as
        sensorValue=analogRead(GSR);
        Serial.print(sensorValue);
        Serial.print(",");
        if ( !ds.search(addr)) {
    ds.reset_search();
    return;
  }

  if (OneWire::crc8(addr, 7) != addr[7]) {
      return;
  }
  // the first ROM byte indicates which chip

  ds.reset();
  ds.select(addr);
  ds.write(0x44, 1);        // start conversion, with parasite power on at the end

   // maybe 750ms is enough, maybe not
  // we might do a ds.depower() here, but the reset will take care of it.

  present = ds.reset();
  ds.select(addr);
  ds.write(0xBE);         // Read Scratchpad

  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();
  }

  // Convert the data to actual temperature
  // because the result is a 16 bit signed integer, it should
  // be stored to an "int16_t" type, which is always 16 bits
  // even when compiled on a 32 bit processor.
  int16_t raw = (data[1] << 8) | data[0];
  if (type_s) {
    raw = raw << 3; // 9 bit resolution default
    if (data[7] == 0x10) {
      // "count remain" gives full 12 bit resolution
      raw = (raw & 0xFFF0) + 12 - data[6];
    }
  } else {
    byte cfg = (data[4] & 0x60);
    // at lower res, the low bits are undefined, so let's zero them
    if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
    else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
    else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
    //// default is 12 bit resolution, 750 ms conversion time
  }
  celsius = (float)raw / 16.0;
  Serial.print(celsius);

    }
    Serial.println("\n");

}

How can I reach the upper format?

From the point of view of what you print, your loop boils down to:
if (millis() - startTime >= MEASURE_PERIOD) {
    startTime += MEASURE_PERIOD;
    sensorValue = ...;
    celcius = ...;
    Serial.print(sensorValue);
    Serial.print(",");
    Serial.print(celsius);
}
Serial.println("\n");

You are printing two newlines on every loop iteration. One is written
as "\n", the other is the “ln” of Serial.println (“println” means
“print some stuff followed by a new line character sequence”). Instead,
you probably want to print a single newline, and only when there is
actual data being printed:
if (millis() - startTime >= MEASURE_PERIOD) {
    startTime += MEASURE_PERIOD;
    sensorValue = ...;
    celcius = ...;
    Serial.print(sensorValue);
    Serial.print(",");
    Serial.println(celsius);  // notice the ln in println
}

But since you are doing nothing else in loop(), you could simplify a
bit and avoid having everything inside a big if statement:
if (millis() - startTime < MEASURE_PERIOD)
    return;

startTime += MEASURE_PERIOD;
sensorValue = ...;
celcius = ...;
Serial.print(sensorValue);
Serial.print(",");
Serial.println(celsius);

Edit: Here is a simple test demonstrating this logic. In both the
second and the third case, it generates an output in the requested
format.
const uint32_t MEASURE_PERIOD = 250;

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

void loop()
{
    static uint32_t startTime;
#ifdef SECOND_CASE
    if (millis() - startTime >= MEASURE_PERIOD) {
        startTime += MEASURE_PERIOD;
        int sensorValue = random(695, 699);
        float celsius = map(sensorValue, 695, 699, 208653, 208777) / 1e4;
        Serial.print(sensorValue);
        Serial.print(",");
        Serial.println(celsius, 3);  // notice the ln in println
    }
#else  // third case
    if (millis() - startTime < MEASURE_PERIOD)
        return;

    startTime += MEASURE_PERIOD;
    int sensorValue = random(695, 699);
    float celsius = map(sensorValue, 695, 699, 208653, 208777) / 1e4;
    Serial.print(sensorValue);
    Serial.print(",");
    Serial.println(celsius, 3);  // notice the ln in println
#endif
}

Why do you say putting the print outside the if will simplify things?

Maybe “simplify” is not the right word, but it will remove one nesting level to most of your code. I (among others) find this is better for readability.

In the second case I have lines like that:
691,690,20.81
The third case doesn't work

@GabrieleGiordano: Then you have either a communication error, or an error somewhere else in your code. C.f. the test I added as an edit.

I think it's much slower than 250ms. If i put 1000 at the beginning, it gives me a print ever 2 seconds I think

In the third code you wrote, the startTime += MEASURE_PERIOD; is just outside the big if?

I confirm the suspect: it's one reading every sec, I compared with data of another sensor that works at 1hz. I had the same number of elements in the array

Precisely it's 2hz instead of 4

@GabrieleGiordano: Your sensor may be slow to respond, or you may have some other problem elsewhere in your program: different problem → different question. The test code above, on my Arduino Uno, outputs 4 lines per second.

the problems seem to be the sensor, that can't read at 4hz

but with another code seems to work. Anyway, its' a matter of another question


text:
What does serial monitor send with 'Both NL & CR'
There is something I don't understand about serial monitor.
As far as I know the Newline option is \n.
The Carriage return option is \r\n.
But does that make the Both NL & CR option \n\r\n?

Newline is \n
Carriage Return is \r
Both NL & CR is \r\n

It would be wonderful if this could be called "CR & NL" (note the sequence) or maybe just say \r\n. Because when you read "Both NL & CR" you then scratch your head and say "hm, does this actually mean \n\r".

"Both" means 1 Carriage Return and 1 Newline (formerly known as "Line Feed"). Our present day "standards" are descended from mechanical teletypes that used those separate codes for the two separate mechanical functions: Returning the print carriage to the left side of the page, and scrolling the paper up one line.
The DOS/Windows world adopted the teletype standard (both) as is.
The unix world dropped the carriage return as unnecessary, letting a single character stand for the end of a line, and more modern hardware (or its software drivers) could figure out what to do for the particular device.
The Apple world chose Carriage Return for its standard back in the mists of time, dropping it in later years for a selectable end-of-line sequence where appropriate, but more usually using the unix standard once it's OSes became hosted on unix.

Baudot had separate CR LF. It was common to use CR and duplicate part of a line to get "Bold" characters.


text:
Arduino Mega2560, Ethernet Shield & OV0706: "Camera not found"
I want to take a picture with the OV0706 and save it to an SD card. I'm using an Arduino Mega2560, Ethernet Shield (with SD slot) and an OV0706. I tried the tutorial for this camera from Adafruit, but I'm still getting a 'No camera found?' error.
I thought it had something to do with assigning the pins, but if I connect the RX from the OV0706 with A15 on the Mega (see picture), it still gives the same error.
// On Mega: camera TX connected to pin 69 (A15), camera RX to pin 3:
SoftwareSerial cameraconnection = SoftwareSerial(69, 3);

The code (important part):
// This is a basic snapshot sketch using the VC0706 library.
// On start, the Arduino will find the camera and SD card and
// then snap a photo, saving it to the SD card.
// Public domain.

// If using an Arduino Mega (1280, 2560 or ADK) in conjunction
// with an SD card shield designed for conventional Arduinos
// (Uno, etc.), it's necessary to edit the library file:
//   libraries/SD/utility/Sd2Card.h
// Look for this line:
//   #define MEGA_SOFT_SPI 0
// change to:
//   #define MEGA_SOFT_SPI 1
// This is NOT required if using an SD card breakout interfaced
// directly to the SPI bus of the Mega (pins 50-53), or if using
// a non-Mega, Uno-style board.

#include <Adafruit_VC0706.h>
#include <SPI.h>
#include <SD.h>

// comment out this line if using Arduino V23 or earlier
#include <SoftwareSerial.h>

// uncomment this line if using Arduino V23 or earlier
// #include <NewSoftSerial.h>

// SD card chip select line varies among boards/shields:
// Adafruit SD shields and modules: pin 10
// Arduino Ethernet shield: pin 4
// Sparkfun SD shield: pin 8
// Arduino Mega w/hardware SPI: pin 53
// Teensy 2.0: pin 0
// Teensy++ 2.0: pin 20
#define chipSelect 4

// Pins for camera connection are configurable.
// With the Arduino Uno, etc., most pins can be used, except for
// those already in use for the SD card (10 through 13 plus
// chipSelect, if other than pin 10).
// With the Arduino Mega, the choices are a bit more involved:
// 1) You can still use SoftwareSerial and connect the camera to
//    a variety of pins...BUT the selection is limited.  The TX
//    pin from the camera (RX on the Arduino, and the first
//    argument to SoftwareSerial()) MUST be one of: 62, 63, 64,
//    65, 66, 67, 68, or 69.  If MEGA_SOFT_SPI is set (and using
//    a conventional Arduino SD shield), pins 50, 51, 52 and 53
//    are also available.  The RX pin from the camera (TX on
//    Arduino, second argument to SoftwareSerial()) can be any
//    pin, again excepting those used by the SD card.
// 2) You can use any of the additional three hardware UARTs on
//    the Mega board (labeled as RX1/TX1, RX2/TX2, RX3,TX3),
//    but must specifically use the two pins defined by that
//    UART; they are not configurable.  In this case, pass the
//    desired Serial object (rather than a SoftwareSerial
//    object) to the VC0706 constructor.

// Using SoftwareSerial (Arduino 1.0+) or NewSoftSerial (Arduino 0023 & prior):
#if ARDUINO >= 100
// On Uno: camera TX connected to pin 2, camera RX to pin 3:
//SoftwareSerial cameraconnection = SoftwareSerial(2, 3);
// On Mega: camera TX connected to pin 69 (A15), camera RX to pin 3:
SoftwareSerial cameraconnection = SoftwareSerial(69, 3);
#else
NewSoftSerial cameraconnection = NewSoftSerial(2, 3);
#endif

Adafruit_VC0706 cam = Adafruit_VC0706(&cameraconnection);

// Using hardware serial on Mega: camera TX conn. to RX1,
// camera RX to TX1, no SoftwareSerial object is required:
//Adafruit_VC0706 cam = Adafruit_VC0706(&Serial1);

void setup() {

  // When using hardware SPI, the SS pin MUST be set to an
  // output (even if not connected or used).  If left as a
  // floating input w/SPI on, this can cause lockuppage.
#if !defined(SOFTWARE_SPI)
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
  if(chipSelect != 53) pinMode(53, OUTPUT); // SS on Mega
#else
  if(chipSelect != 10) pinMode(10, OUTPUT); // SS on Uno, etc.
#endif
#endif

  Serial.begin(9600);
  Serial.println("VC0706 Camera snapshot test");

  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    return;
  }

  // Try to locate the camera
  if (cam.begin()) {
    Serial.println("Camera Found:");
  } else {
    Serial.println("No camera found?");
    return;
  }

Thanks in advance.
(Pictures: http://prntscr.com/apdvi9 )

Since at least my camera needs up to 2 seconds to initialize, I think the
if (cam.begin()) {
Serial.println("Camera Found:");
} else {
Serial.println("No camera found?");

returns immediately what it thinks No camera found
Try it with
    unsigned long timer = millis();
    Serial.println("Camera initializing:");
    while (!cam.begin()) {
    Serial.print(".");
    if (millis()-timer>3000) {
      Serial.println("No camera found?");
      break;
      }
    }

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Using Arduino and XBee at the same time
I have 2 Arduino Unos, 2 XBees and 2 Wireless Proto Shields. The first setup has a humidity/temperature sensor (SHT21P) and it writes data to serial and it works (I've tested it).
Now, the other Arduino with shield and XBee is plugged in my PC to get data from the sensor. So here's the problem: as far as I understand, I can't use XBee and Arduino at the same time, because USB and Arduino both use TX/RX pins to communicate to PC/XBee. I've tested both of the XBees when they are powered with DC jack and they both work. So can anyone confirm that it's true that they're not made for being used by PC and Arduino at the same time? If so, how can I get the data to my computer?

Okay, I guess I figured it all out. So right now I have the following setup:
1 Arduino Board with Wireless Proto Shield (switch in Micro position) and XBee hooked up via DC jack pin, sends data to serial with Serial.print(variable) where variable is a predefined char array.
1 Arduino with Wireless Proto Shield (switch in Micro position) and XBee is hooked to the PC via USB and with Serial.read() I'm able to read data via the Serial Monitor. No configuration required whatsoever, the only thing you need to do this is to declare Serial.begin(9600) to both boards.
So it's true that I can't use Arduino and XBee at the same time, but this still works for me to solve the problem I had.

Please, accept your own answer to close your question.

If I understand correctly your goal is to receive data on your computer from an arduino connected with xbee? You could use a USB > Xbee board similar to Sparkfun's Xbee USB explorer board. I am not familiar with the shield that you are using, but some xbee shields allow you to select the pins that the xbee is connected to. It sounds like yours is defaulting to Pin 0 and Pin 1, hardware serial on the Uno. If you can switch it to Pin 2 and Pin 3 (or any two digital pins) you could use software serial with the xbee, leaving hardware serial free for your USB connection.