text:
How do I use ATTiny pin 5 (RESET) as a digital output?
I am using an Arduino Uno as ISP (Using the standard ArduinoISP sketch) to program an ATTiny13A through the Arduino IDE. (I also have a USBtinyISP 2.0 and a USBASP 2.0, but can't reliably get either to program this chip with any sketch.)
I want to use all six I/O pins on the ATTiny to each control 1 LED. Pins 0 through 4 work fine, but since pin 5 is the RESET pin, it doesn't want to work as an output normally.
I have read from many sources that I can disable the reset pin by changing the fuse bits, and that once I do so I will not be able to program the chip any more. Every source I've seen has given this warning, but has then proceeded to NOT say how to accomplish the 1-time-write.
Assume I've got my sketch exactly 100% as I want it, don't have a high-voltage programmer, and am fine with only being able to program the ATTiny once. How can I program the chip and set the appropriate fuse bits with what I have access to?

Please edit question and list programming-related items in your  “what I have access to” class.  For example, do you have an AVRISP or USBASP or similar ISP programmer?  I assume you don't have an AVR Dragon or STK500 or a high-voltage programmer since you say you don't have a high-voltage programmer. Note, I think  high-voltage programmers can reprogram chips with any fuse settings.

@jwpat7 Done, but I did say I was using an Arduino Uno running the ArduinoISP sketch.

I'm having trouble getting the fuse bits to write; It reads as 0xFF, then writes 0x7F, then reads as 0xFF when it verifies. The output says safemode in several places. Is that preventing the fuse bits from changing?

Found my problem. I needed to set the bit on the other end, that is, change it from 0xFF to 0xFE, rather than to 0x7F. Using http://www.engbedded.com/fusecalc/ helped me figure it out.

RSTDISBL is bit 0 of the high fuse byte. Use avrdude to read the current value of the high fuse byte (-U hfuse:r:-:h), clear bit 0, and then write the value back out (-U hfuse:w:0xXX:m).

Do I program the sketch in Arduino IDE first, then do this? I've never used avrdude directly before, so assume I don't know how to do this.

Yes, since once nRESET is disabled you won't be able to program it without HVSP. Enabling verbose compilation in the IDE should give you the other avrdude options you need to use.


text:
How can I get a unique ID for all my Arduino boards?
Once you have uploaded a sketch to one of your Arduino boards, it is hard to know exactly what source code led to that sketch.
Indeed, you may change the source code of your sketch on your PC without updating it (in binary format) to your board.
I had the idea of setting up a kind of "sketch repository" that would be populated as soon as I upload a sketch to one of my boards. Then I could retrieve, later on, the source code for a sketch running on any of my boards.
For such a repository, I would first need to have an "index" that would enable me to know which board the sketch source code is linked to.
Typically, such an index should be unique for every single arduino board.
Hence my question: how can I get a unique ID for an Arduino board?
Edit:
This is my current list of boards (the miniumum list to be supported by a single unique ID approach):

UNO R3
Mega 2560
Yun
Arduino Robot (that must be 2 Leonardo equivalent boards)

In the future, I may also build my own boards (Uno equivalent but barebones, without FTDI), hence if an approach also supports these that would be better.

@jfpoilpret...just saw this post while perusing the site..did you find a solution, or best case scenario on how to implement this?

There are a number of techniques you could use here to get a unique ID.

FTDI chips have a unique serial number programmed onto them. This can only be accessed from the PC side of the connection as far as I am aware.
Some of the chips with built in USB (e.g. ATmega8U2/16U2/32U2) have a unique ID in the signature data, normally used for USB. Can easily be accessed from both sides of the connection. This includes the ATmega16U2 that is used as the USB->Serial bridge Arduino Uno R3.
Some of the chips with built in USB but no unique ID in the signature will still have a unique ID programmed into the USB stack (e.g. LUFA) used for the bootloader or DFU (Device Firmware Upgrade).
There are many chips with globally unique serial IDs in them e.g. the Microchip 11AA02E48, all of the Dallas 1-Wire sensors (including the common DS18B20 temperature sensor), and other serial EEPROMS. I've used these in production hardware that must have a unique MAC address.
You could modify the standard Optiboot bootloader (or whichever boat loader you use) so that it can hold and respond with a unique ID.

The problem with these is that there is no option except 5 that will work across all boards.
If your solution is going to be a generic one, I would suggest that using a USB ID is not the way forwards. I have ~30 Arduino-based boards, and only 5 of them have built in USB hardware. All the rest of them need an external FTDI cable to be programmed. This means they would all have the same ID.

What do you do with 30 boards?

Mainly for wireless sensor networks. I only have a few real Arduinos - a Duemilanova, a Seeeduino Mega and an Uno. All the others are Teensy, Jeenodes, WiNodes, Nanodes and RFus.

+1 for a thorough list of possible options, thanks! I'd rather avoid 4. as I don't want to add specific hardware to all my boards. 5. looks dangerous (easy to upload the same modified bootloader to 2 different boards) and cumbersome (need to have different bootloaders source code to upload for every board). So far, USB ID and FTDI seem quite good solutions, but do they work with all my current board?

Does Arduino have globally unique serial IDs ? How to read it ?

The chip doesn't have any sort of unique ID as far as I know.... but you could program one into the EEPROM of your boards.
EEPROM documetnation
You would write to a specific address and then future sketches can read the ID and do whatever with it.

You may also be able to see a unqiue ID or address on the host side. I don't know enough about USB devices to tell you more, but the chip handling USB communication might have a unique ID you could use. Your Arduino code would not be able to use this, though.
Alternatively, just use a label maker and put a label on each board.

As far as the unique aspect of the question, a GUID could solve that (within some tiny margin of error).

I had originally thought of using the EEPROM for that; but that requires additional work for every board  get: create a new unique ID, then write it to the EEPROM. Also, there may be incompatibilities with libraries used by my sketches (that may write to the same EEPROM address). Finally in my context, I would need to read the ID from my PC, which is more difficult. The USB unique ID seems more interesting to me.

As per my answer, if you want this to be a generic solution (for most people, and a wide range of boards), relying on the USB ID means that people using FTDI cables on boards without a USB->Serial bridge would not be able to use you system.

Some boards, when connected to a computer, publish their serial number. My Arduino Uno R3 says
[16818.451423] usb 3-2: SerialNumber: 85235353137351E02242

Though I'm not sure how unique it is.

Do all Arduino boards have such a number? It would be nice to have the list of boards that have one (or not).

Looking at mines, 32u4 based ones don't, 328 and SAM3X8E ones do have it

To the best of my knowledge the USB chips all come with a unique serial number, at least for the FTDI chips. On Linux you can easily assign unique device names from that, check my website.
Other than that, what you are describing is pretty much a simple form of version control. Make sure your source files have version numbers. To identify your Arduino, you can make it Serial.Print(); name and version of the code during setup();.

Yes version control is more or less what I want to achieve; but setting a version in code and changing it every time the code changes is not an option (too easy to forget). I currently use github for my sketches, but I'd like to easily find out what version of what sketch is currently running on one board.

There is a macro for compilation date and time __DATE__ and __TIME__. So at least you can automatically store that info in your .hex file @jfpoilpret

Good point, I hadn't thought about these macros for versioning.

I doubt that the USB interface on the Uno gives you a unique serial number. Any number would be part of the code uploaded to the chip which would therefore be the same amongst multiple Unos.
One approach is the DS2401 "Silicon Serial Number" chip which uses the One-wire interface. That would only require one free pin, and some code (the code would be the problem, possibly).
The least intrusive method, and probably the most reliable, would be to simply read back the code and sum-check it. That is exactly what I do with my chip signature detector. However that only detects (as currently written) the bootloader signature. A fairly minor change and it could MD5-sum the entire sketch code.
Example output:
Signature detector.
Written by Nick Gammon.
Signature = 1E  95  0F
Fuses
Low = FF High = D6 Ext = FF Lock = CF

Processor = ATmega328P
Flash memory size = 32768
Bootloader in use: Yes
EEPROM preserved through erase: Yes
Watchdog timer always on: No
Bootloader is 512 bytes starting at 7E00

Bootloader:

7E00: 02 01 02 03 0405 06 07 08 09 0A 0B 0C 0D 0E 0F
7E10: 02 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
7E20: 02 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
7E30: 02 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
...
7FB0: 02 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
7FC0: 02 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
7FD0: 02 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
7FE0: 02 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
7FF0: 02 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F

MD5 sum of bootloader = 56 72 75 2D 5D B5 0D BA 25 10 DF BE 87 D2 A1 27

That MD5 sum (last line) is effectively the signature of that particular bootloader. In fact the most recent version looks them up in a table:
MD5 sum of bootloader = FB F4 9B 7B 59 73 7F 65 E8 D0 F8 A5 08 12 E7 9F
Bootloader name: optiboot_atmega328

So what you could do is, when uploading a sketch, generate a MD5 sum of the hex code. There are fairly simple ways of doing that. Then you could do a "git tag" operation on your source code, and then (using some automated or manual process) remember that a particular MD5 sum of hex code represents the sketch code at a particular moment.
Some sort of database like:
Chip: Uno
MD5 sum: D8 8C 70 6D FE 1F DC 38 82 1E CE AE 23 B2 E6 E7
Sketch: My_robot_sketch_42.ino
Git tag: version666

Now to locate the source from the board, you establish the MD5 sum of the code (by reading it back from the board) and then look it up in your database.

There is tiny library for reading and writing your custom hardware ID to EEPROM. You can use it to avoid pushing wrong sketch to your Arduino or to identify device for other purposes.
https://github.com/skoumalcz/arduino-id-guard
Disclaimer: I'm author of the library :-)

I connected a one wire temp sensor that each come with an unique I'd.  All the sketches read the I'd on boot and wrote the address on every serial connection. I made a shield with all the hardware I needed so if I needed to upgrade from Uno to Mega the device kept its unique I'd.

#include <avr/boot.h>
#ifdef __AVR_ATmega2560__  /// check if a MEGA2560 is in use
#define USEMEGA_ID         ///
void setup()
{
#ifdef __AVR_ATmega2560__
  cli();
  int data3, data4;
  data3 = boot_signature_byte_get(0x04) * 256;
  data4 = boot_signature_byte_get(0x01);
  sei();
  MegaID = data3 + data4;
#endif
Serial.begin(115200);
  Serial.print("MegaID             \t: "); Serial.println(MegaID);
}

// This will show you a 3 digit MegaID
// You can now create different setups for different MEGA2560  with the same source code

The number returned by this code seems to be based both on the device signature (which is the same for all ATmega2560 devices) and the factory-stored oscillator calibration byte (which can vary between boards). It is not guaranteed to be unique. I wonder what is the typical spread of the calibration bytes: this conditions the likelihood of ID collisions.

correct!There only 3 numbers. so they are 999 possibilities. this is not much or secure, but practical, when you have only a few boards an like to have different setups with the same code.

source: Stack Exchange

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

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

sort: votes


text:
Arduino uint8_t to String or char- retrieve from usb device
My code returns uint8_t format when is cast to char and Display on LCD it works fine but I want to get that scanned code for further processing. not only to display on LCD 16x2 , but it returns some strange symbols. Any Idea?
#include <LiquidCrystal.h>
#include <avr/pgmspace.h>
#include <hid.h>
#include <hiduniversal.h>
#include <usbhub.h>
#include <Usb.h>
#include <usbhub.h>
#include <avr/pgmspace.h>
#include <hidboot.h>
#include <SPI.h>
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
USB     Usb;
USBHub     Hub(&Usb);
HIDUniversal Hid(&Usb);
HIDBoot<HID_PROTOCOL_KEYBOARD>    Keyboard(&Usb);

class KbdRptParser : public KeyboardReportParser
{
  void PrintKey(uint8_t mod, uint8_t key);
protected:
  virtual void OnKeyDown  (uint8_t mod, uint8_t key);
  virtual void OnKeyPressed(uint8_t key);
};

void KbdRptParser::OnKeyDown(uint8_t mod, uint8_t key)
{
    uint8_t c = OemToAscii(mod, key);

    if (c)
        OnKeyPressed(c);
}

/* what to do when symbol arrives */
void KbdRptParser::OnKeyPressed(uint8_t key)
{
static uint32_t next_time = 0;      //watchdog
static uint8_t current_cursor = 0;  //tracks current cursor position

    if( millis() > next_time ) {
      lcd.clear();
      current_cursor = 0;
      delay( 5 );  //LCD-specific
      lcd.setCursor( 0,0 );
    }//if( millis() > next_time ...

    next_time = millis() + 200;  //reset watchdog

    if( current_cursor++ == ( DISPLAY_WIDTH + 1 )) {  //switch to second line if cursor outside the screen
      lcd.setCursor( 0,1 );
    }
  char keys=(char) key;
    Serial.println(keys);
// char add =keys.indexOf(5)+keys.indexOf(6)+keys.indexOf(7)+keys.indexOf(8);
    Serial.println(keys);
    lcd.print(keys);
};

KbdRptParser Prs;

void setup()
{
    Serial.begin( 115200 );
    Serial.println("Start");

    if (Usb.Init() == -1) {
        Serial.println("OSC did not start.");
    }

    delay( 200 );

    Hid.SetReportParser(0, (HIDReportParser*)&Prs);
    // set up the LCD's number of columns and rows:
    lcd.begin(DISPLAY_WIDTH, 2);
    lcd.clear();
    lcd.noAutoscroll();
    lcd.print("Scan Your Code");
    delay( 200 );
}

void loop()
{
  Usb.Task();
}

I have some difficulties in following your code, and you include the same file twice. Maybe you can review the code and highlight where the problem lies?

@Bruce I have used this with scanning barcodes with my barcode reader, and it displays the barcode with numbers fine on LCD, but when I see the output of serial monitor, it show some stange symbols instead of numbers that display on LCD

A unit8_t is an 8 bit unsigned integer - it can have any value between 0 and 255, and can be compared to any numeric value in that range.
You can do "further processing" on the received uint8_t value whether it is a printable ASCII value or not.

Bennet I have used this with scanning barcodes with my barcode reader, and it displays the barcode with numbers fine on LCD, but when I see the output of serial monitor, it show some stange symbols instead of numbers that display on LCD

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


text:
unresolved overloaded function type for Wire.onReceive

I am attempting to make an I2C slave out of my Arduino and I can't get past the Wire.onReceive function. Here is my code. The documentation says to just add a function that has the style of void myHandler(int bytes) but I can't figure out why my readPI function does not meet these requirements.
    #include "piCom.h"
    #include "WireAddresses.h"
    #include <Wire.h>

    pi::pi(){
       Wire.begin(NB_INFO); // is 0x04
       Wire.onReceive( readPI );
       //Wire.onRequest(sendPI);
    }

    void pi::readPI(int byteCount){
       while( Wire.available() ){

             ref_IMU = Wire.read();

       }//end while

    }//end readPI

    void pi::sendPI(){

       Wire.write(1);
       //use to send pressure info to pi

    }//end sendPI

    //double pi::getref_IMU(){return ref_IMU;}

then here is the error
piCom.cpp: In constructor 'pi::pi()':
piCom.cpp:7: error: no matching function for call to'TwoWire::onReceive(<unresolved overloaded function type>)'
 Wire.onReceive( readPI );
                        ^

no matching function for call to 'TwoWire::onReceive(<unresolved overloaded function type>)'

Any help is greatly appreciated.

    void pi::sendPI(){

That is a class function (method) which has an implicit this pointer. You can't use it as a static ISR.
In general, classes cannot implement ISRs for this reason. There are a few workarounds, one being to make it a static class function. However then it will affect the entire class, not just one instance.

I ended up just putting the functions inside the .ino file. it's not as neat as I'd like but it works. Thanks for teaching me something new.

You can make a static class function (one that does not belong to a particular instance) and keep the function inside your class then.


text:
FTDI breakout connection
I have been successfully programming UNO boards. I wanted to transfer the project to a Pro Mini. I am using a FTDI breakout. It wouldn't show the device port. I found the device driver I was using was supplied by MatterControl. So I updated the driver from FTDI.
When I connected it I see the port available, but cannot program it. I get
not in sync: resp=0x01 avrdude: stk500_recv(): programmer is not responding

I checked in the device manager and see "USB Serial Port (COM5)" and properties shows "This device is working properly." the provider is FTDI.

This error can come from a number of sources and you'll find this is a common question on arduino.stackexchange. The most likely reasons are:

If the board wasn't reset, the bootloader didn't run;
Rx & Tx connections between the FTDI and the board may be reversed;
Avrdude may be using a different baud rate than the bootloader expects. 57600 baud used to be standard for Atmega328p bootloaders. More recent firmware is using 115200 baud. I've been bitten by this one regularly; my chips have older bootloaders and one of my PCs has a very recent Arduino IDE.

I made the board using the great tutorial by Nick Gammon  for the minimum Arduino board. I got the boot loader to load using Nick's tutorial and then spent a few evenings trying to use FTDI to upload sketches but could not get it to work. In the end, using various bits of inforamtion I found on the web, I made sure the reset signal was coming from the the FTDI (going to low) and then checked the settings of the FTDI and tried to make some changes. I found that the settings in my photos work. Mainly the bit rate 115200 and the latency (m/secs) time to 5 m/secs. The wires from FTDI starting from the top in looking at photo - brown (ground to ground), red (vcc to vcc) orange (tx to rx), Yellow (rx to tx), the other separate orange (was better I used another colour!) is from RTS to reset.
I selected Arduino uno as board and (in my case) COM 10. For me it ow works. I don't know if I would make many of these boars though because of the time and effort. However, itwas a good expeiance and I learnt a great deal. Particularly from Nick Gammon. Thanks Nick!

The problem was resolved by changing "set RTS on close" in the device manager properties as stated here
https://electronics.stackexchange.com/a/87955/80377


text:
Manual reset is required on power on
I am powering a UNO through the 5V pin. I am using a tftlcd shield (2.8" mcufriend.com) on it.
To be able to use the shield with I2C I had to snip the RST leg from the shield. That was done because the shield used A4 which was required for I2C.
 When I power the UNO through the USB port the program starts correctly and a bitmap is loaded onto the screen. When I power up from the 5V pin or the power adapter, the screen remains white. I have to manually press the reset button on the UNO and then the program loads the bitmap.
The ladyAda examples had this to say;
#define LCD_CS A3 // Chip Select goes to Analog 3
#define LCD_CD A2 // Command/Data goes to Analog 2
#define LCD_WR A1 // LCD Write goes to Analog 1
#define LCD_RD A0 // LCD Read goes to Analog 0
#define LCD_RESET A4 // Can alternately just connect to Arduino's reset pin
Adafruit_TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET);

Does that mean I should solder the lcd RST pin to the RESET on the UNO? (if so I am not sure how I can do that without taking the lcd shield to pieces).

It isn't clear from the description whether your setup has a hardware problem or a software problem.  For example, the rationale for “I had to snip the RST leg from the shield” is unclear.
The comment in ladyAda's example, “Can alternately just connect to Arduino's reset pin”, means that it's suitable to hardware-reset the LCD at the same time the Arduino does a hardware reset.  If the “RST leg from the shield” that you snipped is the LCD reset pin, as opposed to a pin driven by the small tactile reset switch on the 2.8" mcufriend shield, you probably should restore that pin.  In other words, unsolder and remove the stub of the pin you snipped off, insert a new pin, and solder it in place.
Note, just reinstalling the pin might make things work.  It's possible the LCD is sitting there in a permanently-reset  state, due to its RST input hanging open.  It's also possible the library is already driving RST properly but that drive isn't getting through, due to the missing pin.  Whatever the case may be, with the pin in place you should be able to software-reset the LCD by pulsing A4.  (Ie, with consecutive digitalWrite() commands, in setup() and before shield initialization, take A4 high and then low, or vice versa.)
Edit: If A4 isn't available for resetting the LCD (due to its use as the SDA signal for I2C, per comment) you might try adding a jumper wire from the shield's LCD_RS pin (above A4) to an available pin, and adjust the #define LCD_RESET statement accordingly.
In general, to add a jumper wire, strip about 5 mm of each end of a short piece of #30 wire-wrap wire.  Form a small hook at each end.  Hold a hook onto the solder of the pin you wish to attach to and briefly heat the solder, letting the hook sink into the solder.  If you don't have wire-wrap wire, use a single strand from some old stranded cable (eg, mouse or keyboard).  Use thin heatshrink tubing or a bit of stripped-off cable insulation to insulate the jumper.  To keep pins in place while soldering, seat the pins being worked on into an old disk-drive connector, or another shield, or if you have nothing else, an Uno.
In your particular case, an mcufriend shield on an Uno, no pins are available unless you co-opt one of the SD-card-slot signals.  But before doing that, it's probably worthwhile to try your original idea of wiring to the Uno's RESET pin.  Your jumper would run from J3's second pin (A4) to J4's last pin (Reset), installed on the LCD side of the shield.  You should be able to see the trace between the Reset pin and the Reset switch, when identifying the Reset pin.

Thanks for taking the time to answer this. To be able to use the shield with I2C I had to snip the RST leg from the shield. That was done because the shield used A4 for RST which was also required for UNO I2C. The shield is actually working correctly, the question is only about the power on. I think if I reconnected the RST then the I2C would cause the LCD to constantly reset.

@PHemans see edit


text:
What Driver IC to use for 40v 2amp DC motor?
I am using a 40v 2amp 3300rpm DC motor for my motor control project via arduino. But i don't know what driver ic to use for driving the motor.any help would be appreciated..

One that can drive 40V 2A. This is what parametric searches are for on electronics suppliers - use them. If you can't find a suitable chip then you can always build your own H-bridge from MOSFETs.

Two minutes with a parametric search told me to use the L298N

Looking on eBay they are available for peanuts from China on a handy breakout board for even easier use.

@Majenko Can i use L298N for direction reversal as well?

It is a pair of full H-bridges. You can use it to drive two motors in both directions independently. Note that the modules on eBay seem to be limited to 35V because of the 7805 on them. Remove that and you have the full 48V range.

It's quite hard, on ebay, to find anything but L298N, once the power envelop swells enough :-)

@Majenko How do i remove 7805..infact what that means?

@AwaisSaifi There may be a switch or jumpers to do it for you. The 7805 is the 5V regulator on the board - the small black square chip thing that is on most of the breakout boards on eBay. If you do have to remove it (no switch or jumpers) then you would, logically, use a soldering iron.

@IgorStoppa not just on eBay :-p

@Majenko I intend to use just the chip not breakout board. Can i do that?

@AwaisSaifi Yes. In that case you don't have to worry about anything except making sure you have a suitable heatsink.

On the board I'm using right now, the 7805 is soldered in a not-so-easy-to-reach position and it's flat, it's using the board itself as both ground and heat sink.
In such case I'd cut the 2 pins as close as possible to the resin package, desolder the 2 stumps and wire out to a separate, discrete regulator. For bonus points, mount it upside down on the heatsink, using the same screw  and hole that the L298N is using. This is the board I'm talking about http://www.photo138.com/0/BOB/CEG007200-D-4.JPG

@Majenko Hmmm and how do i do that. I know i'm being annoying but believe me i'm a beginner and its my final year project and i need all the help i can get and this is the only place.

@AwaisSaifi Crudely: You buy a big heatsink of the right style and attach it with a bolt through the hole.  In detail: You read the datasheet, calculate the thermal coefficients etc and find the right heatsink to dissipate the desired amount of heat in the environment you are running it in. Look at the ones on eBay - you will see the heatsink. The big lump of metal attached to the chip.

@IgorStoppa that would be difficult for me as i want it to be simpler.

@Majenko ok got that.

I'd think it's simpler to rewire 2 pads than design from scratch the board I linked to. Btw, it's 2-sided and has tracks already routed and designed to cope with the currents involved.

@IgorStoppa gotta consider both options. you said you would use a seperate regulator, which one to be exact?

If you check the datasheet for the L298N, it says that the max voltage is 7V, so a 7807 is the simpler choice..
You do not even have to solder anything: as long as you cut the pins of the onboard 7805, you can feed the 7V through the 3rd line of the power connector, which would be usually meant for drawing 5V from the onboard regulator.

@Majenko what if i use a driver with higher parameters like 50v 3amp? Will it work with my motor?

@AwaisSaifi Yes, that will be fine. Those are upper limits of what it can handle - more than that and you risk burning out the driver.

@Majenko Will the motor draw what it needs and not more??

@AwaisSaifi That is correct. You provide the correct voltage (power supply), the motor draws an amount of current (depending on loading). The driver has to be able to cope with those two values. A bit like a pint of beer. You want a pint of beer, and the bar tender is capable of pouring you a pint of beer. As long as what he pours it into is big enough it won't overflow - whether it's a pint glass, or a flagon, it doesn't matter.

@IgorStoppa If i am to rewire the regulator, which regulator should i use?

@AwaisSaifi: did I not answer already?

@IgorStoppa I'm terribly sorry man. I think i'm overstressed about this project. anyways apologies. :)

what if i just join the two pins from where i remove the 7805? @IgorStoppa

If i understood the datasheet correctly, you want the regulated side to be 7V, but joining the 2 voltage domains means that also the input voltage must be 7V

I am assuming since you did not state anything differently you simply want to turn it on or off and possibly PWM to control speed of the motor.  By far the easiest way is to simply use a N-Channel logic level MOSFET.  Connect the Arduino pin of your choice through a 51 (1) ohm resistor to the gate of the MOSFET, also Connect a 10K (2) resistor from the same microprocessor (Arduino) pin to ground.  The "Ground" low side of the 40V power supply needs to be connected to the low side of the Arduino.  The low side of the 40V power supply must be connected to the source of the MOSFET.
Connect the motor from the plus side of the 40V power supply (this will be removed for testing) to the Drain of the N-Channel MOSFET. Last and very important place a diode rated at least 2 amps at 60 volts from the positive side of the poser supply (cathode of the diode, with the band) to the Drain of the MOSFET (anode, no band).
Carefully check your wiring; if it is ok you are ready to test it.  The safest way is to use a led with a 510 ohm in series with the cathode on the Arduino +5 with the positive side of the 40v power supply disconnected.  The anode side connects to the drain of the MOSFET.  When the motor is turned on the LED will light, if it does not reverse polarity of the LED.  As tempting as it might be do not leave the LED connected to the Arduino when the motor is connected.  Up the value of the resistor to about 5.6K and connect it across the motor, it will light when the motor is on.

This helps dampen oscillations
Since the Arduino initializes with all pins as inputs this can drift high, this solves that potential problem which would cause the MOSFET to turn on.
For the MOSFET you need at least 60V with a 10A rating.  This should work with a small heat sink.  If you go to a higher amp rating on the MOSFET it will operate cooler.

Output of Arduino goes to 10K to ground and to a 51 ohm resistor (1/8 W or larger)
The other side of the resistor goes to the gate of the MOSFET.
Ground of the motor power supply, the Arduino and the Source of the MOSFET are connected together.  The 2A diode is connected with the cathode (no band) to the drain of the MOSFET, the cathode (band) is connected to the +40V.  The motor connects from the +40 to the Drain of the MOSFET, reversing the leads will probably reverse motor direction.
Good Luck,
Gil


text:
Low Cost Motorized Valve
I'm looking for a low cost motorized water valve.  I've done a number of searches and have found nothing compelling.  Has anyone here used a motorized water valve with Arduino?  What would you recommend?
A fail-open solenoid might also work but I'd like to try my hand at a motorized valve.
The valves I found start at US$50.  I'm looking for something cheaper.  The purpose is tinkering and I'd like to make an "if water detected - then close valve" sketch.  Ir's simple, just more expensive than I expected.

This is not Arduino-specific. You may find Robotics Stackexchange useful for this question.  More-specific questions are more answerable.

It would help if you could describe what you didn't like about the valves that you found – that would help folks trying to answer understand more about what you want. Specifying what you mean by low cost and what the valve needs to manage (type of liquid, size, operation speed) would also make for better answers.

You can get sprinkler valves, that use solenoids, for under $20 that fit on plastic PVC pipe and are designed for water, such as these at SprinklerWarehouse.  They typically use pipe sizes of about 1 inch.

Right, but I'm looking for a motorized valve or a fail-open solenoid.  I think the lawn stuff is fail-closed.


text:
Renaming pins in sketch
I'm trying to rename pins so that they post as some kind of alpha-numeric combination in a database.  For example, if I define the following....
#define APLHA 0
#define BRAVO 2
#define CHARLIE 5
#define DELTA 6

...I would like to rename the output of the pins, as recorded in the db, as something other than 0, 2, 5, and 6 (or whatever pin is used). Let's say A, B,C, and D for the purposes of this exercise.
Is this just as simple as creating if() function that is called upon prior to posting to the db (ex. if 0 then A, if 2, then B, etc)?  I feel like there must be a better, dare I say more elegant(?), way of doing this?
Current output:
PIN | VALUE
0  |   1
 2  |   1
 5  |   0
 6  |   0
Desired:
PIN | VALUE
 A  |   1
 B  |   1
 C  |   0
 D  |   0

I would like to rename the output of the pins, as recorded in the db - I don't understand this, sorry. You can give pins names, as in your list of defines. What is the issue here?

Why not record the names in the database and let the database do the databasing instead.

Sounds like I'm overcomplicating this.

If I understood your question correctly, you're looking for something like this:
static const byte PIN_NUMBER[4] = { 0, 2, 5, 6 };
static const char *PIN_NAME[4] = { "A", "B", "C", "D" };

// and use them like this:

void Log(byte index)
{
  byte val = digitalRead(PIN_NUMBER[index]);
  Serial.print(PIN_NAME[index]);
  Serial.print('|');
  Serial.println(val);
}

void setup()
{
  for (byte i = 0; i < 4; ++i) pinMode(PIN_NUMBER[i], INPUT);
}

void loop()
{
  Serial.println("PIN|VALUE");
  for (byte i = 0; i < 4; ++i) Log(i);
  delay(1000);
}

Also, in the special case of "A", "B", "C", "D" as pin names, you don't really need the PIN_NAME array, instead of
Serial.print(PIN_NAME[index]);

you can use:
Serial.print('A' + index);

This is exactly what I was looking for!  Thank you.  I'll try it and report back but this looks to be the solution.

authors: Виктор Дерий


text:
Can I set pin 13 to output 5v, then put arduino mini pro to sleep?
Can I set pin 13 to output 5v, then put arduino pro mini to sleep and it maintains 5v going through pin 13 while in sleep mode?
I know there are various "levels" of sleep - can a voltage be maintained on a pin for all/any of the sleep modes?

Sounds like you interpret "sleep mode" as something that disconnects the MCU pins? What does the manual say about this?

@MikaelPatel Actually the manual is quite vague. It's possible to infer that the pins remain connected from the bit that tells you that to save power IO pins should not be driving resistive loads when you enable sleep, but that's about all.

@Majenko Yes, the Pin section of Power Saving is a bit vague but the I/O Ports chapter and circuit diagram gives some more details. Not driving resistive loads is not forbidden but should be avoided in low-power applications. The General Digital I/O circuit does not show any disconnect on sleep mode (which I think was the question).

can a voltage be maintained on a pin for all/any of the sleep modes?

yes.

I will be able to test this tomorrow and update with an accepted answer

Given the absence of clarity on the driving state of pins during sleep, consider connecting Pin 13 to an SR Latch or the gate of a MOSFET.
An SR Latch will hold it's output high or low until a high is presented on the Set or Reset inputs, so connect Pin 13 to the Set input, with a pull-down resistor -- even if the MCU in sleep mode allows the voltage output to drain away to 0v, the SR Latch will maintain it's output.
A MOSFET gate has a non-trivial capacitance which can hold a charge if the gate's driver goes high-impedance, thus holding the gate open after the driver is disconnected.

Thank you for the tips. I've never heard of SR Latches and they seem quite complex - well more complex than the mosfet.


text:
SPST switch - powered from pin output, or voltage regulator
I have a SPST switch and I just want to sense whether it's on or not. I will then turn on/off a relay depending on the state of this switch.
The two options I'm considering are: create a digital out on a pin going to one side of the switch, and read the digital in on another pin off the other side of the switch. Or put 5v from my voltage regulator to the switch, and read a digital in off the other side of the switch.
Would a resistor be necessary for the digital in pin with either of these options?

Why don't you just connect the relay to the switch - no Arduino required?

It is wasting of IO pins to use the digital output pin just to get +5V rail. But both options will work. Don't forget to use pull/up or pull/down resistor, or activate internal pull/up resistor on the sensing pin. When the switch will be open, the input pin is not connected anywhere and will act as antenna, so it might pick up some noise.

I am choosing this as the correct answer because it uses less current when the switch is open.

You could configure one of the digital pins as INPUT_PULLUP and connect one end of the switch to it. The other end of the switch goes to ground. LOW = switch ON, HIGH = switch OFF.
const byte pinNumber = 3;

void setup(){
  pinMode(pinNumber, INPUT_PULLUP);
}

void loop(){
}

Does the pullup resistor draw current continually while the switch is open?

Yes. Approximately 0.1 to 0.25 mA.

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


text:
Reading/Writing Strings with Bluetooth Windows API
I am trying to use my HC05 so my Arduino can communicate with my Windows 10 PC. I have a program written using the Window API for Serial Communication but the problem is it looks like the Arduino/HC05 can only send or the API can only read one character at a time. It is the same with Arduino; I send an entire string with the API and the Arduino has to read/parse it character by character. I was wondering if there was a solution to this problem or if I will need to develop some sort of coding protocol (like space to separate messages) to send messages. (The other issue is that it will take an age to send long messages this way.)
Windows File Reading API
https://msdn.microsoft.com/en-us/library/windows/desktop/aa364232(v=vs.85).aspx
Here is the PC side file.
do {
    // check for data on port and display it on screen.
    ReadFile(file, buffer, sizeof(buffer), &read, NULL);
    int i;
    sscanf(buffer, "%d", &i);
    std::cout << i << std::endl;

    if (read) {
        //WriteFile(screen, buffer, read, &written, NULL);

        //When space seen, add the string to data
        if (buffer[0] == ' ') {
            int convertedDatum = std::stoi(datum, &sz);
            if (convertedDatum < 12) {
                //WriteFile(file, "S " , 2, &written, NULL);
                //WriteFile(screen, "S", read, &written, NULL);
            }
            else {
                //WriteFile(file, "G ", 2, &written, NULL);
                //WriteFile(screen, "G", read, &written, NULL);
            }
            data.push_back(convertedDatum);
            datum = "";

Arduino-side test code
void loop() {

while (true) {
    String sendValue = String(100);
    sendValue.toCharArray(buf, sizeof(buf));

    Serial1.write(buf);
    Serial1.write(' ');
    delay(4000);
}

What I am seeing on the console on the PC which is represented by the screen variable when I debug is when I break at the line
std::cout << i << std::endl;

1-Continue-0-Continue-0
or on the console
1
0
0
0
0
0
...

I am pretty sure that I have seen entire strings sent at once with the Android Bluetooth API so I am not sure exactly if the same can be done with Windows or if the Windows VC++ API's are incapable.

Serial is only ever a character at a time. That is what serial is. If you want to impose some structure on top of that then it is up to you to define that structure.

i guess the real problem is that there seems to be a backup between what is transmitted by the arduino and the point at which it is processed by the PC


text:
Time Library Adjust Default on Windows
Looking at this Time Arduino library because I would like to send time stamps with data across my HC05-PC channel.
https://playground.arduino.cc/Code/Time
I wrote this function to get the time at any point
String getTime() {
    String timeSecond = String(second());
    String timeMinute = String(minute());
    String timeHour = String(hour());
    String timeDay = String(day());
    String timeMonth = String(month());
    String timeYear = String(year());

    String now = timeHour + ":" + timeMinute + ":" + timeSecond + " " +
        timeMonth + "/" + timeDay + "/" + timeYear;

    return now;
}

It seems in the docs he provides info on how to set the default time on a Linux/Unix system so that this library will always be grabbing the correct time by editing some bash files.
When I run the function, having been compiled on Windows, it begins running on 1/1/1970 0:0:0.
He does not provide any documentation for setting the Windows time stamp. How would I go about doing that?

You probably need to show us the code where you receive/set the time.

I don't do an original set. Do you need extra hardware and another library to do that?

AFAIK, no Arduino has an internal clock. So you need to set the library time manually. On the page you link to search for "processSyncMessage". If you want to disconnect your Arduino from the PC after setting the time, I recommend you get a Real Time Clock module.

In that case, I'd have to reset the time before every upload/run?

That's what the example shell script does - sends the PC time to the Arduino.

The Adafruit RTClib has a function to use the compiler date and time. You use the TimeLib maintained by Paul Stoffregen. That library does not have such a function, but you can write it yourself. For example with sscanf and setTime. Without external RTC that will only work if you upload a sketch and keep the Arduino always on. I have a clock like that, and since that clock is always on, I never had the need to add a RTC chip. When the Arduino resets, it returns to the date and time when it was compiled.
If you use a Arduino Due or Zero or M0 then they have their own rtc library.
If you want the computer to send the date and time, then you could make a command and send that via the serial port or via Bluetooth.
What kind of date and time do you want ? The local time, including the offset of the Daylight Saving Time ? That is possible, but not easy to make on a Arduino with RTC chip, in that case it is easier to send a command from the computer with the newest date and time.
It that function okay ? The object 'now' disappeares when the function ends, and yet you return that object.

My issue is that is have this channel between the arduino hc05 chip and my computer. It seems that because only one bit can be transmitted at a time there is a delay in the data being sent from one side to the other. I want to use exact datetime to test this theory but it seems like it is more trouble than it is worth. (I am not going to keep and arduino attached to my laptop 24/7) or buy additional hardware. Running a command line command is a fair option but even that is too extensive for the purposes of the application.


text:
Arduino Nano PWM output acting strange after running for a day or so
I have an Arduino Nano, and I have some issues with it. Basically it needs to control the brightness of a lamp via PWM (plus some circuitry of course). It's hooked up via serial to a little x86 embedded board which runs Linux, and that board is telling the Arduino the desired brightness level (0-255) every 5 seconds over serial. So the only thing the Arduino has to do is retrieve numbers from the other device over serial, and set the PWM output to those values. Here's the code that runs on the Arduino (I inserted some comments so it's easier to read):
Edit: I removed the original code to clean things up as it's not relevant anymore, but you can still view it here.
There's nothing fancy about the code really. It checks for incoming data about 10 times a second, and if there's any, it converts it into an int and sets the PWM output to that value. I know, that part where I manually extract the number characters probably could be replaced by Arduino library calls for cleaner code, but whatever. It works just fine.
The incoming data as I mentioned is the textual representation of an integer ranging from 0-255 followed by a new line character. This data is sent to the Arduino once every 5 seconds.
So whenever I turn this on, it works just fine for a day or so. But this is supposed to be a system that's constantly on 24/7. If I leave it running for a day or so, the output will start acting weird. I already checked, and the values that the other device sends are perfectly normal. It's the Arduino that messes up something. The brightness is NOT what it needs to be. The Arduino is outputting wrong PWM values. If I simply reset the Arduino (without restarting the other device), everything goes back to normal, and it works again for a day, so the problem is definitely in the Arduino somewhere. But I don't think it's in my code. This piece of code looks super simple and innocent, and I bet it is. I have no idea what causes this.
Could this be a hardware problem? I do have another Arduino, so I could try replacing it with that one. I haven't tried that yet since I already put all components in a case, fixed everything in place with screws, and soldered wires directly to the Arduino, so I would rather not replace it if it's not necessary.
So, any ideas on what could cause this?

Update:
I updated the programs on both devices to use a more error-prone protocol for communicating (as suggested here), which is kind of similar to the NMEA 0183 protocol (basically a simplified version of that). The sender sends the data in the following format now:

A single $ character to indicate the beginning of the data
The data itself (which is the textual representation of a single integer)
A single * character to indicate the end of the data
An exactly two digit long hexadecimal checksum value. This is the bitwise XOR of the ASCII codes of all the characters between $ and * (not including those). Letters (if any) are always uppercase.
The packet is finished up with either \n or \r\n

An example would be $178*3E\n, where \n of course means a newline character.
The code running on the Arduino now is the following:
#include <Time.h>

#define _analogWrite(a, b) analogWrite(a, 255-(b))
#define clamp(X, minVal, maxVal) min(max(X, minVal), maxVal)

const PROGMEM int pwmPin = 3;
time_t lastUpdate = 0;
String incoming = "";
int pwmValue = 0;

inline void flushSerialBuffer() {
    while (Serial.available()) Serial.read();
}

void setup() {
    Serial.begin(9600);
    Serial.setTimeout(500);
    pinMode(pwmPin, OUTPUT);
    _analogWrite(pwmPin, 0);
}

void loop() {
    time_t currentTime = now();

    if (Serial.available()) {
        delay(250); // Just to make sure that all data has arrived in the buffer
        incoming = "";
        incoming = Serial.readStringUntil('\n');
        flushSerialBuffer();
        int b = incoming.indexOf('$') + 1;
        if (b == 0) return; // -1 was returned
        int e = incoming.indexOf('*', b);
        if (e == -1) return;
        int checksum = 0x0;
        for (int i=b; i<e; i++) checksum ^= incoming[i];
        String hexString = String(checksum, HEX);
        hexString.toUpperCase();
        if (hexString.length() < 2) hexString = String("0") + hexString;
        if (!hexString.equals(incoming.substring(e+1, e+3))) return;

        pwmValue = incoming.substring(b, e).toInt();

        if (pwmValue < 0 || pwmValue > 255) pwmValue = 0;
        lastUpdate = currentTime;
    }

    if (currentTime - lastUpdate > 30) pwmValue = 0;

    _analogWrite(pwmPin, pwmValue);

    delay(250);
}

It seems like it's working so far, although I'm still testing if this is reliable over a longer period of time. I will edit the question once again to let you know.

Update 2:
Still no success. After a while it just gets stuck on one PWM value and keeps outputting that, regardless of what it receives over serial. It's kind of like it ignores the incoming data after a day or so. I can verify that the other device still sends data correctly, since if I only restart the Arduino, everything goes back to normal.

The Arduino is outputting wrong PWM values; could you be more specific? Does "resetting" the program that is sending the serial data also fix the problem? Just something that I noticed, is that you don't actually check if a newline has been sent. If your loop reads the serial buffer while the x86 is still sending the data, your program could read e.g. 25, while the x86 is trying to send 250\n. Serial.readStringUntil('\n') could help in that case.

@Gerben Please read my comment here

How often are you sending values to the arduino?

It's in the question. Once every 5 minutes. Also, I should say that using Serial.readStringUntil('\n') creates potential bugs. Imagine if the other device sends faulty data, or maybe noise gets into the system, so there would be junk characters after the end line character. That command would only read up until and including that character, but no further. Anything after it would be left in the buffer and picked up by the next iteration of the loop, and that junk data could potentially be converted into an integer causing wrong output.

Edit: once every 5 seconds. Sorry.

You might consider having the Arduino echo back what it thinks it should do, and logging this on the PC.  Then you can very quickly grep the log for any spurious values.

Personally I would get rid of String and use arrays of char. You might be getting memory fragmentation. Also, names starting with an underscore in global scope (eg. _analogWrite) are reserved by the C++ Standard.

Yeah, you might be right. The thing that frustrates me the most about String is that it doesn't have any member functions like string::clear in C++. So whenever I want to get rid of the contents, I just go myString = "" in which case I have no idea what happens to the previous contents. I hope it properly deallocates everything. I would need to look into the implementation of String to be sure. I used it because it was more convenient than raw char arrays. But you might be right. Having everything under full control would be a good thing. I might rewrite it at some point.

After trying the original code using Arduino IDE 1.6.7, I do not see a problem with using up memory.
Depending on the nature of the errors you are seeing, another possible explanation is that you are getting spurious data between real events. If electrical noise or whatever produces one or more characters on the serial line in the long interval between real data points, the current code will treat it as a new data point. If the bogus characters are numeric, they will be sent to the pwm. In the more likely case of non-numeric data, this code converts them to a value of 0 and sends that to the port. This situation is likely if the Arduino is more than a few feet from the PC. A slew rate limited differential driver and receiver like the MAX488 should greatly reduce the chance of this happening. Also make sure there is a good ground between the ends.
You could also reduce the chance of undetected data errors by delimiting your data with something like a '$' to start, then the data, then '*' then a checksum then a newline. The checksum could be simply the sum of all the characters up to the *, truncated to 8 bits and sent as 2 hex characters. This is what the NMEA protocol used by GPS receivers does. At the receiving end you only accept data packets with the proper format and checksum.

The two devices are literally right next to each other, the cable that connects them is about 10 inches long. I don't think it's interference. Although I will implement characters that mark the beginning and end of the data plus a checksum value, that's always a good idea.

I did some modifications to the system based on your suggestions. See the updated part in the question. I'm still testing if it works properly now.

Your problem may be related to the dynamic memory allocation of your String objects. Each time the Arduino receives data, you are creating two new String objects. Perhaps the memory is not being released properly, causing eventual exhaustion of your RAM.
You could make your Strings global and empty them out each time, but a far better solution would be to replace all your string manipulation with a call to Serial.ParseInt() so your big if block becomes
if (Serial.available()) {
        pwmValue = Serial.ParseInt();
        while(Serial.available() > 0 {
          Serial.read();    // flush anything after the integer
        // Save the current time
        lastUpdate = currentTime;
    }
Serial.ParseInt also makes use of the timeout so you don't have to worry about partial values being read.

This is exactly what I did :) See my comment here. I'm still testing it

In the posted code, no String survives the return from loop().

The Strings don't survive but apparently the heap can still get fragmented and eventually run out of space. I have not verified that this is what is causing the problem here, but I think the code I suggested above is more robust.

I tried the original code and it does not appear to have a memory problem. See 2nd answer below.

You have a
race condition in your
code: if you try to read a message while it's being sent, you may catch
only a partial message, and end up reading the wrong numbers. My bet is
that this is exactly what is biting you. Once this happens once, it is
bound to happen again for some time, since 5 seconds is a multiple
of your 100 ms delay.
The right thing to do would be to wait until you get the new-line
character (then you know you have a complete message) before trying to
parse the message. A quick and dirty hack is to just delay(10) after
Serial.available() but before Serial.readString().

Serial.readString() does have a timeout associated with it. In my case it's 250 milliseconds. Which means the following: Serial.available() returns true, indicating that there's incoming data. Then Serial.readString() reads all data that it can read in the next 250 milliseconds which is plenty enough time for the transmission to finish, and the entire data to be in the buffer. This is what guarantees that the entire message is read correctly. So I'm constantly reading the input for 250 milliseconds.

If Serial.readString() did not have a timeout, but instead just read the buffer exactly once, and returned, you would be right. But instead it waits a certain amount of time before returning, waiting for potential incoming data. Since I don't think that transferring a couple bytes at 9600 baud takes anywhere near 250ms, this should be fine.

I checked the source code of Stream::readString(). You are right, it waits for every byte. I thought it would only wait for the first, the documentation is not clear about that. Then, I cannot see the problem with your code. I can only suggest you echo back what you read, with some extra delimiters to show what you interpreted as message boundaries. This could hint you about what is going on.

Yeah maybe. The problem is that it's very hard if not impossible to reproduce the problem on demand. I'll try though.

@adam10603: If you send the messages at a higher frequency, the problem is likely to show up sooner.

I changed the code around, and I ran into some different issues while doing so, but I managed to fix those, so now I have a different piece of code that's seemingly working right now. We'll see how this code performs if I leave it on for a day. I basically changed how the data from the serial port is read and interpreted. Sadly, I'll be leaving for the next week, so I can only get back to this the next weekend. I'll let you know what happened!

Here is the current code I'm trying out


text:
Powering a stepper motor
I'm working on a project where I need a high torque stepper motor. The stepper motor being used is rated at 12 - 24 volts and when I used a 12 volt battery supply composed of 8 AA batteries it appeared to work fine.
Because I wanted higher torque I set the pot on the Easy Driver to 0.5 amps which is within what was recommended for the motor, and used a Lithium Ion battery originally being used for a power drill rated at 18V and 1.5Ah.
When I connected the battery to the easy driver the motor got very hot and would shake when I tried to turn it but not turn. Now the motor will not work with the 8 AA batteries either. Heres a link to the motor US Ship OSM 5:1 Planetary Gearbox Nema 8 Stepper Motor Samll Size High Torque.

What did I do wrong and how can I fix it?
P.S. I am using a photon as the micro controller and the motor is being controlled using the Blynk app I eliminated the chance of it having to do with the photon or Blynk App.
I found out that the battery I'm using is the Makita BL1815 and it is really composed of 2 batteries which are both rated at 15C. I am not sure if C-rating adds or stays the same when you are using two batteries. When I measure the Voltage on the test points I get 4.27V and when using a formula to find current for the Easy Driver I get 0.480A.

In what way is this related to the Arduino?

An rating of 1.5Ah says nothing about the maximal output current of the battery. 1.5Ah states that it could (theoretically) deliver 1.5A over the course of one hour. You might want to re-check your battery pack specs. Since some may have a maximal discharge current rated well below that 1.5A. It's noted by the E-value, 1E would be 1.5A maximal discharge current in this case.
(Probably not the problem here, but it's something)

@Paul I couldn't find an E-value but I think that you meant C-rating because this is all I could find and it seems to be the same thing as what you're saying an E-value is.

C is charge rating, E should be discharge rating. I'm not quite sure if it's documented as so, or that they are generally the same value.

The ratings of the battery are a longshot anyway. Probably not related to your problem, those accu-packs for makita are basically made for this.
And the engine is the one heating up.

How did you set the amps on the http://www.schmalzhaus.com/EasyDriver/ to 0.5A?   What was the voltage at the test point?  The EasyDriver v4.5 schematic says the formula for coil current is A = V/6.  So rearranging, V=A*6, and to get 0.5A, the voltage should be 0.5*6=3V at the motor driver's test point.
The linked motor spec is 0.6A max per coil, and if things went wrong, you could have overloaded a motor.  The 18V battery could have easily provided 1.8 amps to the 10ohm coil in the motor for a bit, before 3x the rated current of the coils would burn it out, or the easydriver went into thermal shutdown or something.
The easydriver looks like it would be capable of controlling the current adequately, but if misconfigured, could easily overcurrent the motor.

When I measure the voltage I get 4.27V. I used the potentiometer on the Easy Driver to adjust the current, and when using a formula I found online to find the current of the Easy Driver I get 0.480A

Try switching back to the situation that did work. To check if something got broken while trying to connect the other battery

The schematic for the easyDriver v4.5 ( https://github.com/sparkfun/Easy_Driver/raw/master/Hardware/EasyDriver_v45_sch.pdf ) says the formula is A=V/6 or 4.27/6=0.712A

Ahhh I see I think that I used a formula for a previous Easy Driver I'll try this out once a get a new stepper motor and see if this solves the issue. Thank you


text:
PPM from remote control is very noisy

I tried to use a function that could smooth out the PPM by using 10 input values and finding the averages. But even this still doesn't seem to be a good way prevent the noise that is occurring when using my Remote. Is there any way to fix this?
Here is the code from the smoothing project. (Although i feel it's not really necessary to add it here, but here it is anyways.)
My code is using the PPMrcIn library. An int is created and then using if statements I make an object do work. My problem is that i have a very small window for work.
My values are between 50 and 200
Where 140 is the preferred midpoint i'd like to work with.
This is my somewhat cryptic number line.
140 is in the middle. Where my window of stability is between 130 and 150
and values below 100 and above 180 are where the robot does some work.

50 ---x---<100-----130--<140>--150----180>---x---200
  /*

    Smoothing

    Reads repeatedly from an analog input, calculating a running average
    and printing it to the computer.  Keeps ten readings in an array and
    continually averages them.

    The circuit:
      * Analog sensor (potentiometer will do) attached to analog input 0

    Created 22 April 2007
    By David A. Mellis  <dam@mellis.org>
    modified 9 Apr 2012
    by Tom Igoe
    http://www.arduino.cc/en/Tutorial/Smoothing

    This example code is in the public domain.

  */

  // Define the number of samples to keep track of.  The higher the number,
  // the more the readings will be smoothed, but the slower the output will
  // respond to the input.  Using a constant rather than a normal variable lets
  // use this value to determine the size of the readings array.
  const int numReadings = 10;

  int readings[numReadings];      // the readings from the analog input
  int index = 0;                  // the index of the current reading
  int total = 0;                  // the running total
  int average = 0;                // the average

  int inputPin = A0;

  void setup()
  {
    // initialize serial communication with computer:
    Serial.begin(9600);
    // initialize all the readings to 0:
    for (int thisReading = 0; thisReading < numReadings; thisReading++)
      readings[thisReading] = 0;
  }

  void loop() {
    // subtract the last reading:
    total= total - readings[index];
    // read from the sensor:
    readings[index] = analogRead(inputPin);
    // add the reading to the total:
    total= total + readings[index];
    // advance to the next position in the array:
    index = index + 1;

    // if we're at the end of the array...
    if (index >= numReadings)
      // ...wrap around to the beginning:
      index = 0;

    // calculate the average:
    average = total / numReadings;
    // send it to the computer as ASCII digits
    Serial.println(average);
    delay(1);        // delay in between reads for stability
  }

also link to my code in github
https://github.com/tisaconundrum2/RCRoomba/blob/master/RCRoomba2.2.ino
Since this is being asked. Let me clarify on this black voodoo thing called a PPM.
Many RC Transmitters and Receivers provide access to the PPM Stream, this is a single stream of pulses which includes the information for all of the receiver channels in a single connection.
The stream is made up of a series of short pulses, the first pulse is the start marker. The time between the start marker and the start of the next pulse defines the pulse length for channel one. The time to the next pulse defines the pulse length for channel 2 and so on. The end of the pulse stream is marked by a gap know as the frame space. This gap indicates that there are no more channels to receive and the next pulse will be the start of a new frame. Each frame contains the pulse widths for all of your receiver channels.
Note - unlike servo signals, in a PPM Stream it is the gaps between pulses that defines the pulse width for a channel, not the duration of the pulse itself which can be very short.
-http://rcarduino.blogspot.com/2012/11/how-to-read-rc-receiver-ppm-stream.html
As discussed above. My PPM signal is highly varied. I want to be able to just get a solid 140. However, the signal will jump irratically between 135 and 142 for reasons I do not completely understand. In an attempt to clear this fuzziness I tried to go for smoothing.

I tried to use a function that could smooth out the PPM by using 10 input values and finding the averages. Could you clarify that somewhat? PPM - is that pulses per minute? Why would you want to smooth it out? a good way prevent the noise that is occurring when using my Remote - what remote?

Sorry, Similar to PWM, but instead Pulse Position Modulation. It's a remote remote controller. I'd want it to smooth it out because i'm getting values that are not within my target range.

Perhaps add a link to what PPM is? And explain it as well? this still doesn't seem to be a good way prevent the noise that is occurring - what noise? Do you mean variations? Or actual noise that is completely different from what you are expecting?

The question has been edited

readings[index] = analogRead(inputPin); - why are you doing an analogRead? That's quite slow (104 µs). Why not digitalRead()? Personally if I was going for highly-accurate readings I would be using an interrupt to quickly note the time the next pulse arrives. delay in between reads for stability - delays here will add to your problems. I think the whole things needs a rework.

First, I want to thank you for making this post. I have a few remote-controlled cars/boats/helicopters, and I've often wondered how the remote control works. :)

To answer your question - and because I was too lazy to work out how to connect to an actual controller - I made a "remote simulator" like this:
// PPM generator

const byte SIGNAL_PIN = 3;
const int SIGNAL_COUNT = 6;
const unsigned long PULSE_WIDTH = 300;  // µs
const unsigned long BLANK_TIME = 25;    // ms
const int widths [SIGNAL_COUNT] = { 600, 2000, 1000, 1500, 2200, 2400 };

void setup ()
  {
  pinMode (SIGNAL_PIN, OUTPUT);
  }  // end of setup

void loop ()
  {
  delay (BLANK_TIME);
  digitalWrite (SIGNAL_PIN, HIGH);  // start
  delayMicroseconds (PULSE_WIDTH);
  digitalWrite (SIGNAL_PIN, LOW);   // end of start pulse

  for (byte i = 0; i < SIGNAL_COUNT; i++)
    {
    delayMicroseconds (widths [i] - PULSE_WIDTH);
    digitalWrite (SIGNAL_PIN, HIGH);  // start of pulse
    delayMicroseconds (PULSE_WIDTH);
    digitalWrite (SIGNAL_PIN, LOW);   // end of pulse
    }  // end of for loop

  delay (1000);
  }  // end of loop

This is intended to generate a series of pulses (six in this case) which might be generated by some fancy toy fun device.

Output from it:

As you can see from the cursor, it is doing what it is bid. The pulse width shown by the scope cursor is indeed 2000 µs, as per the table of widths.
Note: Output on pin 3 on the Uno.

Now we need a decoder. So let's use interrupts:
const byte SIGNAL_PIN = 2;
const int SIGNAL_COUNT = 6;

volatile unsigned long widths [SIGNAL_COUNT + 1];
volatile byte count;

unsigned long lastPulse;

// ISR
void gotPulse ()
  {
  unsigned long now = micros ();

  // a long gap means we start again
  if ((now - lastPulse) >= 25000)
    count = 0;

  lastPulse = now;
  if (count >= (SIGNAL_COUNT + 1))
    return;

  widths [count++] = now;
  }

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  attachInterrupt (0, gotPulse, RISING);
  EIFR = bit (INTF0);  // clear flag for interrupt 0
  }  // end of setup

void loop ()
  {
  if (count >= SIGNAL_COUNT)
    {
    Serial.println (F("Got sequence."));
    for (int i = 1; i < SIGNAL_COUNT + 1; i++)
      {
      Serial.print ("Channel ");
      Serial.print (i);
      Serial.print (" = ");
      Serial.println (widths [i] - widths [i - 1]);
      }
    count = 0;
    }

  }  // end of loop

This uses an interrupt (on pin 2 on the Uno) on the rising edge to detect the start of the pulses. It stores them, and then works out their widths later.

Results?
Got sequence.
Channel 1 = 612
Channel 2 = 2020
Channel 3 = 1016
Channel 4 = 1512
Channel 5 = 2220
Channel 6 = 2428
Got sequence.
Channel 1 = 612
Channel 2 = 2020
Channel 3 = 1016
Channel 4 = 1512
Channel 5 = 2220
Channel 6 = 2424
Got sequence.
Channel 1 = 616
Channel 2 = 2020
Channel 3 = 1012
Channel 4 = 1516
Channel 5 = 2220
Channel 6 = 2424
Got sequence.
Channel 1 = 616
Channel 2 = 2020
Channel 3 = 1012
Channel 4 = 1516
Channel 5 = 2216
Channel 6 = 2432

Highly consistent results, with a small error factor of around 16 µs compared to 600, 2000, 1000, 1500, 2200, 2400

In case it isn't clear, this test required two Unos. One to generate the pulses and a second one to decode them:

The one with the USB cable is the decoder, which writes to the serial port. The other one is powered by 5V/Gnd from the first one, and the white wire is the data with the pulses.


text:
Arduino Serial Monitor
I am currently trying to see the result of a query to a thingspeak field.
This works great when I just use a empty sketch and type the commands manually, but using the following sketch I cannot see the value of +IDP,0,1:1
This means, at field 1, the value 1 is stored. If 0 was stored, it would be +IDP,0,1:0
How it is possible to "ask" if "+IDP,0,1:0" exists at the serial message from the ESP8266? Serial.find does not work....
Here my sketch:
#include<stdlib.h>
#include <SoftwareSerial.h>

SoftwareSerial monitor(2,3); //rx tx
#define SSID "WLAN-0E0265"
#define PASS "2738564673200634"
int ledPin = 13;
String c;
void setup() {
  Serial.begin(9600);
  monitor.begin(9600);
  monitor.println("AT");
  delay(1000);
  monitor.println("AT+CIPMUX=1");
  delay(1000);
  monitor.println("AT+CWJAP=\"WLAN-0E0265\",\"2738564673200634\"");
  delay(5000);
  if(monitor.find("OK"))
    Serial.println("JAP worked");

  monitor.println("AT+CIPSTART=0,\"TCP\",\"api.thingspeak.com\",80");
  delay(2000);
  if(monitor.find("OK"))
    Serial.println("CIPSTART worked");
  monitor.println("AT+CIPSEND=0,110");
  delay(2000);
  if(monitor.find(">"))
    Serial.println("CIPSEND worked");
  monitor.print("GET https://api.thingspeak.com/channels/54209/fields/1/last \r\n");
  delay(10000);
  monitor.println("GET https://api.thingspeak.com/channels/54209/fields/1/last");
  delay(2000);
  String readString;
  ledPin = 13;
  //++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//SEARCH FOR THE :0 or :1                           <-- Here is the problem, rest works fine
  if(Serial.find(":0")){
 //turn pin off
}
  if(Serial.find(":1")){
 //turn pin on
}

}

void loop(){

}

The problem is that you can't use serial's find function to look for one thing or another.  It is a greedy function and it will consume everything coming in to the serial port until it finds what it's looking for or until it times out.  That includes the :1 if you are using find to look for the :0 at the time.
Instead you either need to receive the whole string into memory and examine the string to see what it contains, or you need to manually process the data as it comes in character by character to decide what there is.

Hi thaks for the reply, you mean probably something like this:    if(monitor.available()){
while(monitor.available()){
s = s + monitor.readString(); // monitor.read() will lead to the same result ....
}
}
Serial.println(s);                                         this also does not show up the whole code like I see when I manually type it into the Serial monitor.. I think the Serial.available and serial.find has some timeout or so...

@Merki, if your if statement has no else part, just leave it off.  That is, for a condition c,  the construct  while(c){...} has the same effect as if(c){ while(c){...} } (unless race conditions apply).

You should read this to understand how to read the whole string into memory: http://hacking.majenko.co.uk/reading-serial-on-the-arduino - it's not as easy as you are thinking it is.


text:
Arduino Mega2560 clone responding slowly
I am using an Arduino Mega2560. Using Arduino Mega as ISP to burn sketch, I had loaded the bootloader from Arduino IDE.
I uploaded the blink LED code to the Mega. But the LED is responding slowly. Same with Serial code. Delay of 0.1 second acting as 1 second on my board. In code serial communication baud-rate is 9600 but I am getting proper value when I set the baud-rate to 4800 in serial monitor.
Could anyone point out the problem?

If Your Clone is slow. Then Replace it..Clones are very cheap to replace.

Either your fuses are wrong (set to 50% the real speed of your crystal / ceramic resonator), you're using the internal oscillator instead of the expected external one, or you have the wrong board with the wrong F_CPU value selected in the IDE.
Check all of those carefully.

thanks Can you let me know the fuse values, coz i had not change any thing in boot loader. also can you let me know how to choose external or internal oscillator

http://www.avrfreaks.net/forum/fuse-bits-mega2560-arduino


text:
How to mimic soft-power button in inexpensive toys & flashlights?
My kids have a few odd inexpensive toys with a soft push-button that will turn on the toy, and subsequent pushes change the toy's mode of operation in some fashon.  A flashlight comes to mind, where the button is pushed once and it turns on, push again and it blinks, and a 3rd time and the light turns off.
I've looked inside one of these flashlights, and there's a small blob covering some IC, what looks to be a diode, and the usual connections for the batteries and lights.
How do these circuits "work" without immediately draining the batteries?  I'm looking to mimic this behaviour on a battery powered arduino Uno (or possibly Pro Mini).
What comes to mind is that the button is on an interrupt line, which wakes the system up from some sleep state..  when the button cycles around to an "off" state, the system goes back to sleep.

I have a lengthy write-up about saving power at Power saving techniques for microprocessors.
One of the sample sketches on that page (Sketch J) does what you ask:
#include <avr/sleep.h>

const byte LED = 9;

void wake ()
{
  // cancel sleep as a precaution
  sleep_disable();
  // precaution while we are doing other things
  detachInterrupt (0);
}  // end of wake

void setup ()
  {
  digitalWrite (2, HIGH);  // enable pull-up
  }  // end of setup

void loop ()
{

  pinMode (LED, OUTPUT);
  digitalWrite (LED, HIGH);
  delay (50);
  digitalWrite (LED, LOW);
  delay (50);
  pinMode (LED, INPUT);

  // disable ADC
  ADCSRA = 0;

  set_sleep_mode (SLEEP_MODE_PWR_DOWN);
  sleep_enable();

  // Do not interrupt before we go to sleep, or the
  // ISR will detach interrupts and we won't wake.
  noInterrupts ();

  // will be called when pin D2 goes low
  attachInterrupt (0, wake, FALLING);

  // turn off brown-out enable in software
  // BODS must be set to one and BODSE must be set to zero within four clock cycles
  MCUCR = bit (BODS) | bit (BODSE);
  // The BODS bit is automatically cleared after three clock cycles
  MCUCR = bit (BODS);

  // We are guaranteed that the sleep_cpu call will be done
  // as the processor executes the next instruction after
  // interrupts are turned on.
  interrupts ();  // one cycle
  sleep_cpu ();   // one cycle

  } // end of loop

According to when I tested that, it used 0.116 µA when asleep (116 nA). That is well below the rate at which batteries self-discharge.
Basically that code does what you described. It sleeps, when pin D2 goes low it wakes and flashes an LED.
I should point out though that any "development board" Arduino with a voltage regulator, USB interface, and power LED on it will consume considerably more power because of the current drain they consume.
For low-power applications you need the bare chip (with appropriate supporting circuitry, like decoupling capacitors).

Long time fan of your powersaving page, have posted it as an answer to many a question here :)

Thanks! I actually improved the above code today. First, I changed the LOW interrupt to FALLING, as we now know that a FALLING interrupt will wake the processor. And FALLING is better because if you hold the button down you don't get multiple interrupts. Also, I re-measured the idle power. My page had it as 0.35 µA, but with better testing equipment I now measure 0.116 µA. That's pretty low. :)

Wow, thanks!  Quite a comprehensive write-up on your site.  I'll do some learnin' on using a bare chip, instead of the Pro Mini or other boards.  Thanks again!

I have made a circuit in the past that does more or less this:

There are two switches in the diagram - the one on the top right turns the circuit on, and the one lower-middle turns it off. Once turned on, it will stay on until the bottom switch is pressed.
The two resistors bottom left, and the switch at the bottom, represent your Arduino.
Note that, this diagram is OUTSIDE the arduino - it provides power TO the Arduino (and any other components relating to your project). That is, the bottom of the 1MOhm resistor, and the bottom of the left transistor, connect to the power pin on the Arduino. Those two resistors don't literally, exist.
It works as follows: The transistors do pretty much all the work. Both transistors work as switches. At the start (as shown in the diagram), both transistors have the same voltage at the base, and the emitter (the top one +5v between top and center/left; the bottom one 0v between center/right and bottom). This turns both switches off, and preserves the status quo, and consuming nearly no power.
As soon as the switch at the top is closed, the base (center/right) of the lower transistor is pulled up to +5V, switches this transistor on, and power can flow from this collector to the emitter. This means power can flow through the TOP transistor from emitter (top) to base (center/left), switching on the TOP transistor. This allows power to flow from the emitter (top) to collector (bottom). This takes over from the pushbutton, keeping the bottom transistor on. This is the other stable state.
At this point, power goes to the Arduino (bottom two resistors, representing load, and bottom switch, which is one of the pins on the Arduino. This pin should be set to "high impedance" until the Arduino wants to switch itself off, then it should go low.
I built the top part of the circuit, with an LED for the bottom half (both switches were just wires), and it worked, but I'd have to consider what would happen if the arduino pin is high or low while the top button is being pressed.

Interesting. Can you measure the idle power consumption?

Don't know how. All the power for everything runs through the top transistor, so I guess it would be the leakage on an transistor at cutoff? On the other side of it, when powered up, it should run emitter -> collector through the top transistor, then through the base of the lower transistor, so there should be no resistance. I don't know how it would work in practice when switching on/off, and what happens when both switches are closed - I guess the resistor at the top would protect it?

The disadvantage of this technique is that it requires an external signal to activate it, since the arduino (or whatever else) gets NO power at all until fired up.

Don't know how. - set the whole thing up, then instead of connecting your power supply to the 5 V input point, connect via your multimeter in milliamps range. If you aren't sure of the technique, Google how to do current measurements - you don't want to blow the fuse in your meter.

I know how to measure power consumption, and I will try it, but my simulator shows in the picoamps. I guess the leakage of the top transistor at cutoff? I will experiment with my simulator when I get a chance. My simulator says the above circuit (off) leaks 15pA.

I should point out that the question was about a single button. Still, it's always interesting to experiment with low-power techniques. :)

Let us continue this discussion in chat.


text:
Can I use a 3.3v GPIO to control an opto-isolated 5v relay board?
I am working on a DIY home automation project using a Wemos D1 Mini as the controller, and I ordered some 4-channel 5v-triggered relay boards. The ESP8266 that Wemos D1 Mini's are built on has GPIO output voltage of 3.3v, ostensibly too low to trigger the relays.
I've read a Reddit post that was saying that as long as you use a separate 5v power suppy for the relay board, 3.3v should be enough to trigger the relays. Is that accurate, or do I need to use a transistor or something to provide the relay board inputs with 5v?

Yes, the Reddit post's approach is likely to work ok, as long as you correctly follow the cautions in it:  • connect the VCC pin of the relay board to a 5V source,
•  connect together the Arduino ground,  the relay ground, and the  5v-source ground.
Here is a typical relay-module circuit diagram (for one channel):
(Note, this diagram is from a home automation blog; for more discussion and similar diagrams, see eg
4-relay-shield-diagram at yourduino.com and stripboard-shield-relay-sm at startingelectronics.org.)
As you can see in the diagram, the Arduino pin that connects to JP2-2 will not be exposed to voltages.  (The base of an NPN transistor effectively is at the junction of two back-to-back diodes.)
When the Arduino or ESP pin at JP2-2 is at about 0 V (ie, when the Arduino pin is off) IBE=0; that is, no Q2 base-emitter current will flow; thus, Q2 will be off, so that both of LED1 and relay U1 will remain off.
When the Arduino or ESP pin at JP2-2 is at about 3.3 V (ie, when the Arduino pin is on) IBE is about 2.5 mA, which should be enough to reduce VCE to about 1 V, leaving 4 V across the relay coil, or enough to turn it on.
Note, the 2.5 mA figure for this circuit is calculated as follows:  IBE = (3.3-VBE)/1000 - VBE/10000 = (3.3-0.7)/1000 - 0.7/10000 = .00260 - .00007 = .00253 A = 2.53 mA.  Note that the alternate circuit diagrams linked above don't have a 10KΩ resistor like that in the diagram above, so instead of about 2.5 mA would have about 2.6 mA drive.
If for some reason you don't have quite enough base drive – in which case you might be able to hear a slight click from the relay, even if it doesn't switch – you could increase the "5 V" line into the LED and relay to say 5.5 V or 6 V.  As noted before, the  back-to-back diodes structure of the NPN transistor will isolate that voltage from your Arduino or ESP.

Just to assure the OP - every 5V relay I've used works fine with 3.3v for the "trigger"

Short answer : it will probably work.
If your relay board is opto-isolated, there is a small potential risk that 3V3 may not be enough to lit the optocoupler sufficiently, you will have to test it.
The reddit board is not using optical separation but only a transistor, like on the schematic of the answer above,. In that case, 3V3 is always enough to saturate the transistor. Anything above around 1V5 would probably do, but this can vary according to the resistors, relay consumption and transistor gain.
There is an extensive discussion of this topic at https://www.forward.com.au/pfod/HomeAutomation/OnOffAddRelay/index.html#Mods3v3


text:
USB Keyboard in Retro Emulators
I have created a retro keyobard using a ZX spectrum and a PRO MICRO based on the info here: http://blog.tynemouthsoftware.co.uk/2013/04/arduino-leonardo-based-zx81-usb-keyboard.html
When plugged into my laptop or a raspberry PI it works fine. However, when running any of the emulators like FUSE it doesn't work at all.
Can anyone explain why this is and what I have to do to make it work? Searching around on the web I see it has something to do with the key mapping which I can understand for when I do shifted keys but why it doesn't work when I just press p is eluding me.
EDIT:
When using a USB sniffing program I can see that my "real" keyboard sends 0x8 bytes for an 'a' 00 00 04 00 00 00 00 00
BUT my arduino sends 0x9 for an 'a' 02 00 00 04 00 00 00 00 00
Snippets of the the code I am using is
// keyMap and keyMapShifted are both 2D arrays of type byte
byte keyMap[8][5] = { {'5', '4', '3', '2', '1' ....etc
byte key = shifted ? keyMapShifted[[r][c] : keyMap[r][c]
Keyboard.write(key)

Ideas? A Bug? Do I have to rewrite Keyboard.write?

Does a normal USB keyboard work with these emulators?  If not, then the question is off-topic here and belongs a support site for the emulator.  But if a usual USB keyboard does work, then the reasons why yours doesn't seems on-topic, and you should probably start by trying to use logging software to see the key codes it sends vs the ones your implementation sends.

Yes the normal keyboard works 100%. OK I will have a look at finding some logging software. Thanks!

OK using a USB sniffing program I can see that mky "real" keyboard send 0x8 bytes for an 'a' 00 00 04 00 00 00 00 00

BUT my arduino sends 0x9 for an 'a' 02 00 00 04 00 00 00 00 00 The code I am using is Keyboard.write(key) where key is of type byte and is assigned by byte key = shifted ? keyMapShifted[[r][c] : keyMap[r][c]. keyMap and keyMapShifted are both 2D arrays of type byte initialised by (for example) byte keyMap[8][5] = { {'5', '4', '3', '2', '1' ....etc

Edit this into your question, don't try to squeeze it into comments

Still no further along with this. Can anyone even direct me to where the code lives that ultimately sends the keycodes so I can see whether it is a simple fix to drop the leading 02?

In the library source, presumably.

Yes I am hoping someone could direct me to which of the files as there are many and I have so far been unable to identify where in the code these bytes are generated. I am not getting any ideas from the Arduino forum either.


text:
Print string from arduino to serial monitor
I want to send text over serial monitor to Arduino and make Arduino return that string back to me over serial monitor.
I have made this function which reads from serial input and returns a string object.
String readSerial() {
    String input;
    while(Serial.available() > 0)
        input.concat(Serial.read());
    return input;
}

In the loop() I have:
if(Serial.available()) Serial.print(readSerial());

If I just do something like Serial.print("Hello world!"); everything is fine. But, if I try to return string object I get lot's of numbers.
I guess Serial.print doesn't know how to read String object and returns ASCII codes of characters or something?
[update]
I have checked it, and it's indeed outputing ASCII codes. For Hi I get 72105.
[update]
I have updated my readSerial function to use this :
input += (char)Serial.read();

But now I'm getting carriage return and new line after every character:
[SEND] Hi
H(CR)
i(CR)

So, how can I make it return my text so that is readable?

String.concat() takes a String as the second argument. Serial.read() returns an int. The compiler creates code that converts the int into a String similar to this:
input.concat(String(Serial.read()));

This is not what you want.
Let's tell the compiler what you really want instead:
input.concat((char)Serial.read());

This will tell the compiler to do the following:
input.concat(String((char)Serial.read()));

We are now having the compiler call the correct String constructor, and the code will work as we expect.

Yes, just figured that out. Thanks anyway.

Answering the other part of the question:

you're getting CRs because your readString is just wrong.

The problem is that you don't wait for receiving a whole line of string. For example, if you press H on the serial monitor, then it is getting received and echoed back as if it would been the whole input, ending with a new line.
You might wish to check my answer at Get strings from Serial.read() that is use https://www.arduino.cc/en/Serial/ReadStringUntil which reads you the whole string until a separator (for example the whole string until it ends with a CR when you press Enter on the serial monitor).


text:
Keyboard Control Not Working As Intended
I'm trying to control a single motor.
If I press 'a', then motor 1 should turn to 0, if I press 's', then motor 1 should turn to 180
#include <Servo.h>

char key = 0;
const unsigned int BAUD_RATE = 9600;

Servo Servo_0;

void setup()
{

  Servo_0.attach(0);
  Servo_0.write(0);

  Serial.begin(BAUD_RATE);

 // Serial.println("      Arduino Serial Servo Control");
 // Serial.println("Press < or > to move, spacebar to center");
 // Serial.println();

}

/*
a - 97
s - 115
d - 100
f - 102
*/

void loop() {

  if(Serial.available()>0)
  {
      key = Serial.read();
      Serial.print("I received: ");
      Serial.println(key, DEC);

     if(key == byte(97))
     {

       Serial.print("Turning Motor 1 to 0 deg");
       Servo_0.write(0);

     }
     else if(key==byte(115))
     {
       Serial.print("Turning Motor 1 to 180 deg");
       Servo_0.write(180);

     }

     delay(1000);
}

But what is happening is that the motors are barely turning after I enter the key onto the Arduino monitor interface. Can anyone diagnose as to what might be happening?

Why not if (key == 'a')?

Hi, I've changed my code to that statement but it still doesn't turn as intended

You say motors, but do you mean servos?  If you put in some servo write commands in setup(), worth a 5 second delay after each do they move?

Does anyone know if I must use "Processing" in order to activate keyboard control??

The problem I see is that your servo is attached to pin 0.
Pins 0 and 1 are used by arduino unos and megas for serial communication, so you can't output to a motor and send/receive serial at the same time. Try moving the servo to pin 3 and see what happens.
In response to your comment, any character sent from any terminal (or other piece of hardware) will work; you do not need to use Processing to communicate with an arduino.


text:
How to detect pinout at run-time
Is it possible to query the pin-out and each pin's attributes at run-time with Arduino?
If not, can it be done at compile-time?
Finally, if not, how can I incorporate this kind of information into my project to avoid completely rewriting my program for each possible Arduino model?
I am looking for something like this:
PinProperties props= getPinProperties(pinNumber);

props.supportsDigitalInput();
props.supportsDigitalOutput();
props.supportsAnalogInput();
props.supportsAnalogOutput();
props.supportsPWM();
props.analogInputBits();
props.analogOutputBits();
props.pullupResistance();
props.pulldownResistance();

etc.
NOTE: This question is similar and I might use the board model to look up a pre-stored pin-out.

I did not know about it! Moderators,  please migrate this question!

It's a nice thought, but I'd suggest this could most practically only be done at compile time (selecting an Arduino model based on cpu ID).   The only situation where you'd actually need this would be if you deployed the same firmware image to multiple cpu ID's ...but that seems beyond the expectations of the Arduino dev environment.

I am actually going this route in my project.  The idea is to abuse Arduino to the benefit of the ease of use for end user.

pins_arduino.h has some standard macros that can be used for some of what you're looking to do. Using the arduino:standard variant used by Uno for example:
https://github.com/arduino/Arduino/blob/1.8.1/hardware/arduino/avr/variants/standard/pins_arduino.h#L35:
#define digitalPinHasPWM(p) ((p) == 3 || (p) == 5 || (p) == 6 || (p) == 9 || (p) == 10 || (p) == 11)

Or if you want to use your naming scheme:
#define supportsPWM(p) digitalPinHasPWM(p)

After that it gets a bit more sketchy:
https://github.com/arduino/Arduino/blob/1.8.1/hardware/arduino/avr/variants/standard/pins_arduino.h#L28
#define NUM_DIGITAL_PINS 20

So, assuming that Arduino digital pins will always be numbered consecutively from 0 and any pin that supports digital input also supports digital output(which is the case in any variant I'm familiar with), you could use that to write some macros:
#define supportsDigitalInput(p) ((p) < NUM_DIGITAL_PINS)
#define supportsDigitalOutput(p) supportsDigitalInput(p)

https://github.com/arduino/Arduino/blob/1.8.1/hardware/arduino/avr/variants/standard/pins_arduino.h#L29
#define NUM_ANALOG_INPUTS 6

Could be used to write this macro(with numbering assumption):
#define supportsAnalogInput(p) ((p) < NUM_ANALOG_INPUTS)

Note that this will not work for the An analog pin names(e.g. A0 vs 0).
As for:
props.supportsAnalogOutput();
props.analogInputBits();
props.analogOutputBits();
props.pullupResistance();
props.pulldownResistance();

I'm don't know of pre-existing code for those. There is probably a way to get it for the first three in an architecture specific manner. The last two you'd most likely need to get the information from datasheets for all of your target microcontrollers and define then using processor specific macros.

Finally, if not, how can I incorporate this kind of information into my project to avoid completely rewriting my program for each possible Arduino model?

The libraries are designed so that you don't really need to know that. One issue is the relationship between the chip pins and the board pins. Just as an example, pin 19 on the Atmega328P goes to the board pin 13 (digital pin 13) on a Uno.
If your program needs a couple of digital inputs and a couple of digital outputs, you could use (say) D2 and D3 as inputs and D4 and D5 as outputs. Then let the underlying libraries work out which chip pin that is, and configure it correctly when you use digitalRead, digitalWrite and pinMode.
You can self-query for the chip type (for example here) however that doesn't tell you what board the chip is mounted on.

to avoid completely rewriting my program for each possible Arduino model

What are you envisaging that would require a complete rewrite? Many libraries and projects are written to work on multiple boards with only minor changes (if any). You can detect the processor type at compile-time.
I simply don't see where "complete rewrite" comes into it. Use functions to abstract out the parts that interface with pins (as digitalRead, digitalWrite and pinMode already do) and a few constants at the start of the code to indicate which pins you have chosen for this particular board.

Sorry ,I should have explained better. My program is datadriven so that the serial protocol will tell it which pins to use for what. To make that happen it needs to know which pins are available, and what they can be used for. So instead of maintaining many images, I would like to maintain only ONE that adapts to the current hardware.

I see. Well, different Arduinos have different processors. For example ones like the Atmega2560 have different addressing models internally than the chips with less RAM. Your goal of sharing a single executable amongst various processors is probably not very achievable. It's like hoping to run Windows software on OS/X.

There is no strong relation with pin numbering and the hardware as far as I know.
To be more specific, the datasheet tells you what registers can be used for what functions. The microcontroller does not neccesarily know what registers it has or what functionality it's registers have.
You could make your own library or class for a pin.
I would go by something like:
Pin input1 = new Pin(.....);

if(input1.isAnalog()){
   input1.setupAnalog();
}

if(input1.analogIsReady()){
   input1.readAnalog();
}

Instead of having a "pinproperties" object for a pin.
You'll have to look how you want to make the class.
You can create one single class that has all functions and just checks if there is an implementation for that pin.
You may go by classes like:
class pin

class analogPin extends pin

class pwmPin extends pin

However, this may fail if your analog pin doesn't support the regular "pin" functions (like I/O).
Theoretically you could use C++'s multiple inheritance to inherit things as I/O, PWM and Analog, but I've heard that it doesn't perform very well on embedded targets.

Alternatively you could make a list of pins that support PWM. And a list of pins that support Analog. And a list of pins that support I/O.
When a person (runtime) tries to set a pin's state, you can check if that pin supports I/O, but I'm not sure what behaviour you'll expect if one tries to set a pin that doesn't support that option.