text:
How can my library source code instantiate an object from another library?
I'm having trouble explaining my issue. What I'm doing is creating a library to work easily with the RFID reader/writer RC522 module. I need to create an object of the library MFRC522 in my .cpp file to be able to communticate with the module itself. I want my constructor end up like this:UltimateRFID rfid(53, 5);, the parameters being the slave select and the reset pins, respectively.
The problem is that I don't know how to make my constructor so that it is within the scope of the functions that require the MFRC522 object to be called. Below's my code.
#include "Arduino.h"
#include "UltimateRFID.h"
#include <MFRC522.h>

MFRC522::MIFARE_Key key;

UltimateRFID::UltimateRFID(int ss, int rst)
{
   MFRC522 mfrc522(ss, rst); //this would be ideal, but how can my functions access the instance?
}

void UltimateRFID::initialize() //sample of a function that uses the MFRC522 object
{
  //digitalWrite(49, HIGH);
  digitalWrite(2, LOW);
  for (byte i = 0; i < 6; i++) {
    key.keyByte[i] = 0xFF;
  }
  mfrc522.PCD_Init();
  if ( ! mfrc522.PICC_IsNewCardPresent())
  {
    return;
  }
  if ( ! mfrc522.PICC_ReadCardSerial())
  {
    return;
  }

}

Now comes my header file, although I'm not sure it matters much.
#ifndef UltimateRFID_h
#define UltimateRFID_h

#include "Arduino.h"
#include <MFRC522.h>

class UltimateRFID
{
  public:
    UltimateRFID(int ss, int rst);
    void initialize();
  private:
    MFRC522::MIFARE_Key key;
};

#endif

Please be patient, it's my first library.

Why not have your class just extend the MFRC522 class?
#include <MFRC522.h>

class UltimateRFID : public MFRC522 {
    private:
        MIFARE_Key key;

    public:
        UltimateRFID(uint8_t ss, uint8_t rst) : MFRC522(ss, rst) {}
        // your other methods
        void initialize();
};

void UltimateRFID::initialize() {
    //digitalWrite(49, HIGH);
    digitalWrite(2, LOW);
    for (byte i = 0; i < 6; i++) {
        key.keyByte[i] = 0xFF;
    }
    PCD_Init();
    if ( ! PICC_IsNewCardPresent()) {
        return;
    }
    if ( ! PICC_ReadCardSerial()) {
        return;
    }
}

UltimateRFID rfid(53, 5);

void setup() {
    rfid.initialize();
}

void loop() {}

Your class then becomes a "flavour" of MFRC522 with additional functionality. It can access all the public functions of the MFRC522 class, since they are now a part of your class.
Anything you can do with an MFRC522 object you can now do with your object. As well as your extra functions.

And I don't need a constructor in my source file? Only in the header?

You can have a constructor if you want. There is an empty one in the header at the moment (the {}). No content is needed since the initialisation list calls the parent constructor for you.

I did just that and I get a compilation error: collect2.exe: error: ld returned 5 exit status.

Did you copy and paste my code? I just noticed a typo in the initialisation list. I am not at my computer at the moment (1:48am here) so cannot test it right now.

I did copy it, fixed the typos (MFRC522 instead of MRFC22/MRFC622) but the error appears anyway.

Strange. It compiles for me. You are including the MRFC522.h in both the library and sketch, aren't you?

To be sure I have updated my example into an SSCCE.

Still get that error, and now it appears in every sketch. But that's for another day. Thanks for your answer.

While @Majenko's answer is probably best (I +1'd it), for completeness, here's how to construct a member variable with parameters:
class UltimateRFID {
    public:
    UltimateRFID(int ss, int rst) : mfrc522(ss, rst) {}

    protected:
    MFRC522 mfrc522;
};

"placement new" is another option:
class UltimateRFID {
    public:
    UltimateRFID(int ss, int rst) {
        new (&mfrc522) MFRC522(ss, rst)
    }

    protected:
    MFRC522 mfrc522;
};

However, this method calls the default ctor - which may or may not be an issue. This is usually reserved for re-initializing an existing object.
There's also assignment:
class UltimateRFID {
    public:
    UltimateRFID(int ss, int rst) {
        mfrc522 = MFRC522(ss, rst)
    }

    protected:
    MFRC522 mfrc522;
};

This also calls the default ctor and works best if the class provides operator=.

UltimateRFID::UltimateRFID(int ss, int rst)
{
   MFRC522 mfrc522(ss, rst); //this would be ideal, but how can my functions access the instance?
}

As you note, that instance would go out of scope immediately. The simplest thing would be to put a pointer to the other class in your class definition. Then in your init function do a new to create the instance of the class, passing the appropriate parameters.

In init and in all other functions that use MFRC522 objects?

No, you only do a new once (for a particular instance). Read up on new/delete in C++ tutorials.


text:
Burn smell from arduino uno
I have did something stupid.. I connected 10K Ohm potentiometer at its maximum value PARALLEL with a LED. The positive long leg of the led to arduino 5v and the negative leg to the GND.
After giving arduino 5v from USB Mobile Charger ( Output: 5V , 1A ) I smelt a burn and quickly removed the charger from the outlet.
I waited a few hours and connected the arduino ( without any components ) to the charger again. and the arduino worked. I then connected it to the PC and uploaded the blink sketch of the on-board led and it worked !
Then I uploaded a sktech for blinking led on other pins and it worked also !
My question is:
1) What is damaged on the board ?
The smell is near the regulator but I'm not sure if it's from the regulator itself or just a component near it.
2) Can it be safe to still using the arduino board on USB Power or Battery Power without any problems ?

One can only speculate, especially with regard to the current condition, but it's likely that either F1 was activating or T1 was getting hot.   Excessive current consumption can be a result from past damage, however it is also quite possible that the reset behavior you see with a 9v battery has nothing to do with this incident, and everything to do with the fact that 9v batteries are very weak and a poor choice for powering an Arduino.

I think it probably did not damage any components, and the smell probably came from the plastic that started to burn because of the high current, but for sure if you left a little more, something could have been damaged. To be sure only by testing component one by one.

@ChrisStratton
I didn't understand what F1 and T1 are ?
I don't use batteries for powering my arduino but just wanted to test the external power. You may be right about the 9v battery, but what about the burn smell ?

@AndrewPaes
What plastic part do you mean ? on the board ?
I don't know how can I test component. I don't even have voltmeter and such measuring tools. :(
But the smell is from the regulator or just something near it. I can't determine.

Could it be that the reverse polarity diode failed closed with high resistance?

What is "the reverse polarity diode" ?

That burn is likely the smell of the potentiometer, not the arduino. I would check the arduino with a multimeter set to resistance to make sure that the Vin trace resistance is nominal.

No. the smell isn't from the potentiometer.
the smell was from the LED and the board itself.
I can smell it when I get near to the regulator but not sure if it's from the regulator itself or something near it.

@Youssef13 what voltage are you feeding the arduino?

I used a mobile charger that outputs [ 5V - 1A ] into the USB port ( the same port is used to connect arduino to PC for programming )
If that has nothing to do with the regulator then the smell is just near it.
It's away from the microcontroller the the pins

@Youssef13 do you have a multimeter?

Unfortunately, I don't have one :(

@youssef13 i highly recommend you pick one up when you are able to. For a basic meter, you can get for 20$ https://www.amazon.com/dp/B000EVYGZA/ref=cm_sw_r_cp_apa_1XqBzb4SXP6GD

source: Stack Exchange

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

sort: votes


text:
MAX7219 powered on via digital pin set to HIGH is not working good (I < 25mA)
I'm using 7-segment 8-digits MAX7219 eBuy module in my battery-supplied ATMega168P project to output some readings. MAX7219 in powerdown mode draws ~150uA (as stated in the datasheet) which is too much for me, because the rest of the circuit draws less than 1uA is sleep mode. So I decided to power off Vcc line for MAX7219 before entering sleep, and power it on just after wakeup.
Current draw for the software-dimmed display module is only 15..19 mA in my case, which is far less than 40mA pin maximum for ATMega168P, so I connect display Vcc line to one of digital pins and power it on at setup():
void setup()
{
  pinMode(4, OUTPUT);
  digitalWrite(4, HIGH);
}

However, display module works only 1..3 seconds after starting, then switches off. I checked display Vcc — 4.9V, but the display is off. (I turned off enterng to sleep mode for a while)
This display module doesn't have capacitors C3 and C4 between Vcc and GND (but there's a placeholder for it), recommended in some sources. I solder two capacitors of 100nF and 4,7uF in parallel. It helps only a little: after 1..2 seconds of normal working display shows only digit #0 and in much higher brightness than I set (see the photo).

I may only suggest my cheap multimeter is wrong and the display draws much more, but I dont know how to check it. Rset is 10k on this module, btw.

Why does it happen?
Is there a way to solve the issue without using a transistor / MOSFET / relay (I suppose it should obviously help).

EDIT: If the display is powered directly by controller Vcc it works correctly as expected. It's current draw is 15..20mA.

Well, the average current might be about 20mA. But peaks will be much higher. Simple mosfet for switching power will be much better.

Thanks, @KIIV ! This is obvious solution and I'm going to try some 2N3904 as a power switch here. But I'd like to understand the reason of issue: high current draw or some noise from ATMega168 pin or smth else...

After some research I eventually solved my problem, so here's the answer.

Why does it happen?

This LED display draws much more current than I measured on Vcc line between Arduino and display because of ghost powering via signal lines (DIN, LOAD, CLK). The display (although slightly dimmed) can even run without Vcc line connected! Real current draw was about 30-40 mA with peaks up to 100 mA.

Is there a way to solve the issue without using a transistor / MOSFET / relay (I suppose it should obviously help).

Yes, by limiting display current draw.
For an unknown reason these cheap MAX7219-driven LED boards has very small current control resistor RSet of 10 kOhm, resulting in huge Iseg ~= 40 mA. Replacing it by something like 62k will limit per-segment current to ~10 mA.
This is what the datasheet says:

And this is how it can be done:

Works perfectly! Now I can power off LED display completely, so it consumes no current when the device is sleeping.
NOTE: it's important to properly re-initialize MAX7219 after power on!
In the colorized table above one could find display current draw for different software-set intensity settings in case of using RSet = 62k. GND line values (blue column) seems to be correct as they well correspond with overall device's current draw (the most correct measurement, I suppose).

Using a led display in a low current application is an oxymoron. An LCD display is more appropriate.
With that said, you can switch the the 7219 from the high side and turn the pins into input mode to avoid ghost powering.
Od mode works but pull up has to be switched as well.

Thanks for replay!
Sorry, what is "od mode" and what kind of pull up you mean here?
I do digitalWrite(LOW) for display data pins now to avoid ghost-powering. Is it enough or I'd better change pin mode to INPUT?

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


text:
Issues uploading to atmega324pb w/ adruino as ISP
I've been having some issues programming a new atmega324pb I have on a custom board. I set up an old adruino UNO as an ISP by uploading the ArduinoISP sketch, setting the programmer to "Arduino as ISP" and then using the "Upload using programmer" option but to no avail. Here is the verbose error message that the console logs:
System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : COM5
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200
     AVR Part                      : ATmega32U4
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PA0
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : STK500
     Description     : Atmel STK500 Version 1.x firmware
     Hardware Version: 2
     Firmware Version: 1.18
     Topcard         : Unknown
     Vtarget         : 0.0 V
     Varef           : 0.0 V
     Oscillator      : Off
     SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.03s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

I think it might be an issue with Arduino possibly targeting a chip other than atmega324pb that I'm using, but I'm not sure. I don't know of any official arduino boards that utilize the 324pb. The main issue that I see is that avrdude can't find the device signature. I've see others mention it might be faulty wiring, but I made sure all connections are intact.

Welcome to Arduino Stack Exchange.  Please take the tour at https://arduino.stackexchange.com/Tour to get the most out of this site, and to see how to attract the most useful answers.

In case anyone was wondering, I solved the problem.
Unfortunately I wasn't able to figure out how to upload it using Arduino as ISP, but I was able to get it to work with an AVR Pocket Programmer from Sparkfun. If you decide to use this, check out this drivers guide. It will It'll save massive headache getting the usb device to be recognized.
IMPORTANT FOR ATMEGA324PB USERS!!!
The atmega324pb is apparently not a default microcontroller in avrdude. You need to add it to the toolchain manually. You can do this by following this blog:
https://hackaday.io/project/9313-uino-mini-super-atmega328pb/log/31003-easy-way-to-a-toolchain-for-the-atmega328pb
It is the same process to add any Microchip microcontroller to avrdude, so this guide will work for the atmega324pb (did it firsthand). From there, you can also add a custom entry to Arduino's boards.txt config file if you'd like to use the Arduino IDE for development. I didn't mind working the command line, but having it in Arduino definitely streamlines the proccess of compiling the .hex and uploading it in one go.
Here is the custom entry I added to Arduino's boards.txt file for the Atmega324pb. All the data was gathered from the datasheet:
####   ATmega324PB    ####
m324p.name=Atmega324pb
m324p.upload.via_ssh=true

m324p.vid.0=0x0424
m324p.pid.0=0x2740

m324p.upload.tool=avrdude
m324p.upload.protocol=usbtiny
m324p.upload.maximum_size=28672
m324p.upload.maximum_data_size=2560
m324p.upload.speed=57600
m324p.upload.disable_flushing=true
m324p.upload.use_1200bps_touch=true
m324p.upload.wait_for_upload_port=true

m324p.bootloader.tool=avrdude
m324p.bootloader.low_fuses=0x62
m324p.bootloader.high_fuses=0xD9
m324p.bootloader.extended_fuses=0x0f

m324p.build.mcu=atmega324pb
m324p.build.f_cpu=1000000L
m324p.build.vid=0x0424
m324p.build.pid=0x2740
m324p.build.usb_product="Arduino m324pb"
m324p.build.board=AVR_m324pb
m324p.build.core=arduino
m324p.build.variant=standard
m324p.build.extra_flags={build.usb_flags}

Note that I set the upload.tool to avrdude, and the upload.protocol to usbtiny since I was using the pocket AVR programmer.
IMPORTANT!!!  The high fuse bit in this config also is 0xD9, instead of the default 0x99. I changed one fuse bit to disable JTAG and regain access to GPIO pins. To my knowledge Arduino wasn't setting fuse bits when uploading with the programmer, but this is an important note to take. If you need to use GPIO pins that share JTAG functionality, run the avrdude command line to set the high fuse bit appropriately. (0xD9 for me).

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


text:
Sending POST request to HTTPS aws server using SIM900A
I have hooked up an SIM900A module to my Arduino UNO and I wanted to send a GET request to my aws server for which I have created a RESTful API, the problem is that when I send a request using AT commands I get 601 error code. But I am easily able to connect to https:// www.goolge.com and get the HTML page. I have seen some other links which are very much technical for me like https://stackoverflow.com/questions/39177095/unable-to-invoke-aws-api-gateway-get-url-with-gprs-connection and https://electronics.stackexchange.com/questions/266974/testing-a-connection-to-a-tcp-socket-through-sim5320a-cellular-module.
I want to know if SIM900A even support connections to HTTPS and if yes, how can I connect to my aws server. I kind of a noob in networking, so sorry if I cannot elaborate on details. I have read somewhere online that SIM900A only supports half https, I don't know what that means, any help/advice would be helpful.
AT commands I used
AT
AT+CGATT = 1
AT+SAPBR=3,1,"CONTYPE","GPRS"
AT+SAPBR=3,1,"APN","www"
AT+SAPBR=1,1
AT+SAPBR=2,1
AT+HTTPSSL=1
AT+HTTPINIT
AT+HTTPPARA="CID",1
AT+HTTPPARA="URL","https://www.google.gom"
AT+HTTPACTION=0
AT+HTTPREAD

Did you really mean to include a link to www.goolge.com? (which I've deliberately not made into a link here) Or did you mean to link to Google?

https://stackoverflow.com/questions/15975051/error-httpaction0-601-0 also, edit your question to add your code. Also check a few more https and http sites, to see if there is a pattern.

@Paul I have tried and I am able to connect to all tried HTTP sites and few HTTPS sites, I have added the code, I want to know how to connect to an AWS server.

Have you tried issuing the command AT+HTTPSSL=? to make sure your device supports SSL. You can also try the command AT+HTTPSSL=1 to force SSL on if it isn't already. You can query the current mode with AT+HTTPSSL?

Maybe the websites support HTTP fallback, but Amazon AWS doesn't? Or it uses another more advanced certificate or encryption?

@SpeedOfSpin Yes I have used AT+HTTPSS=1 before sending the request

@Paul can you please elaborate, what you have said?

There are different types of SSL, maybe your device does not support what AWS is trying to give https://www.globalsign.com/en/ssl-information-center/types-of-ssl-certificate/ But that's more of a guess.

@Paul Thank you, the problem is that AWS can't accept the request in SSL send by SIM module, can you put the answer with your explanation and know how to configure AWS for accepting HTTP request.

I actually have no knowledge on configuring AWS, nor do I think that it's related to Arduino (you may find better explanations on the AWS support portal). If you've found the solution, you can also post it yourself, then please note the steps that worked for you, so that others can use this information once they find themselves in the same situation.

When you use https, you must not use:
AT+HTTPPARA="URL","https://www.google.gom"

You must use:
AT+HTTPPARA="URL","www.google.gom"


text:
Serial doesn't initialise on Arduino Mega 2560 when not powered via the USB port
I am working on a project with a Mega 2560 and a Sim800L module.
Everything works fine, however if i don't connect the USB port (at least once) and power only externally (either by Vin unregulated 7-12V or 5V regulated pin)
the program will seem not to initialize serial in setup().
I found this which is related to the issue but not a proper workaround:
https://forum.arduino.cc/index.php?topic=24642.0
edit: I can confirm using a resistor to short pins 0+1 together (serial) works but it is not a proper solution. This means you have to disassemble your project to access the resistor or add a switch if you want to use USB to debug later or upload new code. Another workaround which i need to test is to remove all Serial code (because i can in my specific project), but again this is not a proper solution.
Any ideas please?
edit2:
for comments
if(SIM900.available()>0){
// AT command to set SIM900 to SMS mode
SIM900.print("AT+CMGF=1\r");
delay(100);
// Set module to send SMS data to serial out upon receipt
SIM900.print("AT+CNMI=2,2,0,0,0\r");
delay(100);
textMessage = SIM900.readString();
textMessage.toUpperCase();
Serial.print(textMessage);
delay(10);
}

if(textMessage.indexOf("SET PHONE")>=0){
// Set phone number to receive notifications
phoneNumber = textMessage.substring(9,21);
Serial.println("Phone number set to: " + phoneNumber);
String message = "Notification number set to: " + phoneNumber + "\nSend 'Help' for additional commands.\nNote in case of reset number returns to hardcoded default";
sendSMS(message);
Serial.println("Confirmication of phone number change sent");
textMessage = "";
}

so why the softwareserial tag? Sim800 is on Serial1/2/3? do you use some old AVR core version or IDE?

That link is 13 years old and I did not hear about that pin 0/1 trick recently. Do you have such an old Arduino board? Are you sure the USB controller (ATmega16U2 ?) does not get its Vcc HIGH via Vin?

You did not provide any code, so we have to guess. Do you print to the Serial Terminal on your PC/Laptop in the Sketch. The if you don't connect the Arduino with the PC you do not establish the serial connection to the terminal. Perhaps you added a blocking command, that waits for the connection.   Connecting Pin0 and Pin1 simulates the Terminal connection and the blocking code does not block. If I'm right, a solution would be to remove the blocking code. But I don't know code, so I can't tell you how,

@juraj Because i use softwareserial to connect to sim800. I converted it to hardware serial as a test and it works but needs some more changes

@DataDiffler My board is not old, i can check if that's the case

@Peter Paul Kiefer Yes i print without checks. Some parts of the code in loop work so it doesn't make sense for me to need checks. In fact the part that doesn't seem to work checks for softwareserial buffer, not serial so i don't think there is any blocking. Here's an example of the non-working part of the code (didn't debug if both of the blocks don't work):

I would be more interested in the setup method. Where the Serial.begin  is located and all location where Serial is used. Perhaps a while ( ! Serial.available() ) or something else. Can you switch the onboard LED to ON in the first if block above, to see if it is entered at all. And the Software serial can also stop the program and wait for a connection.

Nothing special other than setting initial values and pins, just Serial.begin(57600);  and  SIM900.begin(57600);. I could use while (! Serial); everytime i want to print but i believe this doesn't work on Mega, right?

@DataFiddler Checked (i have 2 here) both are clones using the C340G instead of ATmega16U2 for UART to USB and it is powered normally. Problem is that if i have serial.print functions seem to make the program not able to function normally unless serial is connected. Functions inside the program that don't have serial.print code in them (like sendsms function) work normally and the loop continues to work.

never use SoftwareSerial on Mega (it is not the cause of your problem, only something that doesn't make sense)

the ATmega2560 doesn't know if USB is connected. it sends the data and doesn't care what happens with it. there is no UART flow control to block the transmitting.

@juraj yeah i already converted it today to use hardware serial, i just used software serial since i knew it should work 100%. I know mega2560 doesn't know if usb is connected but i don't know why serial.print will break the program if it's not connected to anything. They say it's because the RX0 pin is floating when not connected. So is there is a way to keep serial.print inside the code and ignore it when not connected?

I think i know a bodge solution..wire the DTR pin into one of the digital inputs and read it when i want to print in serial..

RX and TX of ATmega2560 is connected to the USB chip's RX and TX and this connection is active. no floating pins

@Juraj After doing several checks with Serial disabled and running functions to check if DTR is open or closed i found the issue wasn't caused by this. Posted explanation and answer below!

Ok i found the issue and the solution.
For some reason it seems that while the MCU is running Setup(); hardware or software serial don't work properly.
In my case i have code that set the SIM module to SMS mode and to send those messages to the serial port.
For some reason it doesn't send them (or probably the module is not ready to accept them).
Connecting the USB cable reset the arduino and run setup() when opening the serial monitor setting the module in the correct mode.
Adding this code in the main loop solves this issue even though i have them powered both by the same step down converter.
edit: That turns out 1 hour later after debugging more is not exactly a proper solution to the issue.
 That command to set into SMS mode only works when you are connected to the network.
I have a check for that and a reset function.
So now at Setup() i wait 10s for the module to boot up so it is ready to open a serial port, then i check if it is connected to the network before i send the commands to set into SMS mode.
Example:
// Initializing serial commmunication
Serial.begin(57600);
delay(10000);

while (ini){
    Serial3.begin(57600);
    delay(1000);
    Serial3.print("AT+CGREG?\r");
    delay(100);
    netStatus = Serial3.readString();
    if (netStatus.charAt(22) == '5' || netStatus.charAt(22) == '1') {
         digitalWrite(LED_NET, HIGH);
         ini=false;
         }
    else {
        digitalWrite(LED_NET, LOW);
        digitalWrite(resetPin, LOW);
        delay(2000);
        digitalWrite(resetPin, HIGH);
        delay(30000);
        }
}
  Serial.print("SIM800 ready...");

  // AT command to set SIM800 to SMS mode
  Serial3.print("AT+CMGF=1\r");
  delay(100);
  // Set module to send SMS data to serial out upon receipt
  Serial3.print("AT+CNMI=2,2,0,0,0\r");
  delay(100);

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


text:
Save some arduino pins when driving a 4 digits 7 segments display
I built a simple clock using a 4 digits 7 segments LCD display. I display one digit at a time, switching on and off very quicky and cycling through digits.
Everything is ok, but I used 8 + 4 = 12 arduino pins. I need 2 more pins for other features and I don't want to use 0 and 1 as I need onboard programming features of Arduino Mini.
I used I2C for RTC clock, I could add some interface here (like a PCF8574) and get some pins from here. But I'd like a different (and more educational, for me) approach.
Is there an IC that sends an HIGH output on one of four output pins driven by 2 input pins? I need this:
IN     OUT
P0 P1  D0 D1 D2 D3
0  0   1  0  0  0
0  1   0  1  0  0
1  0   0  0  1  0
1  1   0  0  0  1

This way I can connect OUT to digit selection and spare 2 pins.
Thanks for your hints.

A 2-to-4 line decoder should do what you need. I've used a 74HC139 with Arduino before, which contains two decoders in a 16-pin DIP.
There are lots of other options though. In the past, I've used an 8 bit serial-to-parallel shift register (74HC595) to control a 7 segment display. It effectively lets you control 8 (or more) outputs using only 3 pins on your microcontroller. You have to be careful of power requirements though. Most shift registers aren't able to drive such a display directly, but I was able to incorporate transistors quite easily to get around that.

I already have transistors for driving digits as there could be up to 8 segments lit (7 segments + dot). I guess I need to add 74HC139 before transistors and let it operate with low current. Thanks for your precious hint!

With 74HC595 solution I would need a transistor per segment, right? This could become complex with 32 transistors. I'd go for 74HC139 solution.

@Ghigo - Since you're only displaying one digit at a time, you should only need 8 transistors for the segments.

In this case I need to put 74HC595 after transistors. Some current will flow there. From datasheet I see 20mA is the limit when switching. Is this correct?

@Ghigo - You can connect the Arduino directly to the 595 without any difficulty. The transistors should go between that and the display. Each output on the 595 can usually only manage around 6mA on its own at 5V.

I think you'll neeed 4 additional transistors (in addition to the 8 first ones, one per segment): one for each digit common cathode (or anode, based on your displays), as for a chip, sourcing current is the same as sinking current, which means you may fry the circuit on the other end of the LED...

Are you using your analog pins?  Did you know they can be used as digital pins?

The analog pins can be used identically to the digital pins, using the aliases A0 (for analog input 0), A1, etc. For example, the code would look like this to set analog pin 0 to an output, and to set it HIGH:
pinMode(A0, OUTPUT);
digitalWrite(A0, HIGH);

This is your best bet if you aren't using all your analog pins.

Inreresting. I have 2 unused analog pins I can try to use them for display as I require a pwm pin. Never tried this

+1 for referencing them by their analog assignment (A0) instead of digital (14) et al which isn't always correct.

I know it's not what you asked, but you're using a lot of pins, why not try streamlining them and go to an I2C backpack? This one from adafruit includes a single 4x7 segment display.
given your comment, another option would be an I2C/SPI 7 Segment driver. (datasheet).
new edit: Actually, when I posted the above 7 segment driver, this is the one I was thinking of. I don't know why I didn't find this the first time.
max7219/7221 datasheet and digikey source:

Thanks for the hint. My display is bigger than this and I wanted a more educational approach. I would like to keep display driver part directly on Arduino as I already have implemented automatic brightness control with a photoresistor and some lines of code.

@Ghigo I just posted an update for a 7 segment driver that may be of use as well.

It says no longer manufactured, but there are clones. Interesting approach.

I don't know why I posted that first driver, that's not the one I have here. I have one of these on a breakout board with 8 x 7 segment displays. Works a treat!

An I2C IO expander might be your best bet.  If your existing I2C device uses a different address, you may be able to put both devices on the same I2C bus.  You would then use 0 additional pins compared to your current design.

Just noticed you've already considered this approach - I'm gonna leave this here anyway for other folks reading too speedily.


text:
Executing multiple functions/commands on Arduino
I am using an RFduino and an iOS application to control some RGB LEDs.
This is how I'm sending a string command to the module:
- (IBAction)fadeButtonPressed:(id)sender {
    [rfduino send:[@"fade" dataUsingEncoding:NSUTF8StringEncoding]];
}

These command(s) are coming back just fine on the RFduino side:
void RFduinoBLE_onReceive(char *data, int len) {
  if (strncmp(data, "fade", 4) == 0) {
    // begin fading chosen LED colour
  }
}

Is there a better way of executing multiple functions on Arduino? It seems to me that there should be a better way of doing what I'm trying to do.
Originally for example I was getting an issue where the "fade" string was coming back as "fadek" so I used strncmp(data, "fade", 4) instead of strcmp(data, "fade") and this fixed the issue.
I guess I'd like a way of cleaning up my code and perhaps make it easier to introduce new bits of functionality depending on which strings are coming back.
The functions I would like to be able to do would be controlling of the RGB colours and then Fading or Blinking that particular chosen colour.
What if I wanted to introduce faster blinking? Rather than setting another command integer and adding another condition is there a cleaner approach?
The selection of the colours is set by selection of a color wheel within my iOS application. This is working fine. The problem is that the Blinking and Fading does not blink/fade the selected colour (command 0).
Here is my entire sketch so far:
#include <RFduinoBLE.h>

// Pin 2 on the RGB LED.
int rgb2_pin = 2; // red
int rgb3_pin = 3; // green
int rgb4_pin = 4; // blue
int brightness = 0;
int fadeAmount = 5;

// Command properties.
int command = 0;

void setup() {
  // debug output at 9600 baud
  Serial.begin(9600);

  // Setup the LEDs for output.
  pinMode(rgb2_pin, OUTPUT);
  pinMode(rgb3_pin, OUTPUT);
  pinMode(rgb4_pin, OUTPUT);

  // This is the data we want to appear in the advertisement
  // (the deviceName length plus the advertisement length must be <= 18 bytes.
  RFduinoBLE.advertisementData = "rgb";

  // Start the BLE stack.
  RFduinoBLE.begin();
}

void loop() {
  if (command == 1) { // Fade in/out chosen colour.
    analogWrite(rgb2_pin, brightness);
    analogWrite(rgb3_pin, brightness);
    analogWrite(rgb4_pin, brightness);

    // Change the brightness for next time through the loop:
    brightness = brightness + fadeAmount;

    // Reverse the direction of the fading at the ends of the fade:
    if (brightness == 0 || brightness == 255) {
      fadeAmount = -fadeAmount ;
    }

    // Wait for 30 milliseconds to see the dimming effect
    delay(30);
  } else if (command == 2) { // Blink
    digitalWrite(rgb2_pin, HIGH);
    digitalWrite(rgb3_pin, HIGH);
    digitalWrite(rgb4_pin, HIGH);
    delay(200);
    digitalWrite(rgb2_pin, LOW);
    digitalWrite(rgb3_pin, LOW);
    digitalWrite(rgb4_pin, LOW);
    delay(200);
  }
}

void RFduinoBLE_onConnect() {}

void RFduinoBLE_onDisconnect() {}

void RFduinoBLE_onReceive(char *data, int len) {
  Serial.println(data);

  // Each transmission should contain an RGB triple.
  if (strncmp(data, "fade", 4) == 0) {
    command = 1;
  } else if (strncmp(data, "blink", 5) == 0) {
    command = 2;
  } else { // Change colour.
    // Reset other functions.
    command = 0;

    if (len >= 3) {
      // Get the RGB values.
      uint8_t red = data[0];
      uint8_t green = data[1];
      uint8_t blue = data[2];

      // Set PWM for each LED.
      analogWrite(rgb2_pin, red);
      analogWrite(rgb3_pin, green);
      analogWrite(rgb4_pin, blue);
    }
  }

  Serial.println(command);
}

+1 for the way you've posted your question. I hate it when people don't write comments in their script. But you did write comments!

Ended up going with something like this:
#include <RFduinoBLE.h>

// State properties.
int state = 1;
char command;
String hexstring;

// RGB pins.
int redPin = 2;
int grnPin = 3;
int bluPin = 4;

// Setup function to set RGB pins to OUTPUT pins.
void setup () {
  pinMode(redPin, OUTPUT);
  pinMode(grnPin, OUTPUT);
  pinMode(bluPin, OUTPUT);

  // This is the data we want to appear in the advertisement
  // (the deviceName length plus the advertisement length must be <= 18 bytes.
  RFduinoBLE.deviceName = "iOS";
  RFduinoBLE.advertisementInterval = MILLISECONDS(300);
  RFduinoBLE.txPowerLevel = -20;
  RFduinoBLE.advertisementData = "rgb";

  // Start the BLE stack.
  RFduinoBLE.begin();
}

void loop () {
  switch (command) {
    case 1:
      // Blink.
    break;
    case 2:
      // Fade.
    break;
  }

  //RFduino_ULPDelay(INFINITE);
}

// Converts HEX as a String to actual HEX values.
// This is needed to properly convert the ASCII value to the hex
// value of each character.
byte getVal (char c) {
  if (c >= '0' && c <= '9') return (byte)(c - '0');
  else return (byte)(c - 'a' + 10);
}

// Process each function/command.
void processCommand (int command, String hex) {
  switch (command) {
    case 'b':
      command = 1; // Set blink mode.
    break;
    case 'f':
      command = 2; // Set fade mode.
    break;
    case 'c':
      // We put together 2 characters as is
      // done with HEX notation and set the color.
      byte red = getVal(hex.charAt(1)) + (getVal(hex.charAt(0)) << 4);
      byte green = getVal(hex.charAt(3)) + (getVal(hex.charAt(2)) << 4);
      byte blue = getVal(hex.charAt(5)) + (getVal(hex.charAt(4)) << 4);

      // Set the color.
      setColor (red, green, blue);
    break;
  }
}

// Sets the color of each RGB pin.
void setColor (byte red, byte green, byte blue) {
  analogWrite(redPin, red);
  analogWrite(grnPin, green);
  analogWrite(bluPin, blue);
  delay(200);
}

// This function returns data from the radio.
void RFduinoBLE_onReceive (char *data, int len) {
  for (int i = 0; i < len; i++) {
    stateMachine(data[i]);
  }
}

// Main state machine function, which processes
// data depending on the bytes received.
void stateMachine (char data) {
  switch (state) {
    case 1:
      if (data == 1) {
        state = 2;
      }
    break;
    case 2:
      if (data == 'b' || data == 'f' || data == 'c') {
        command = data;
        hexstring = "";
        state = 3;
      } else if (data != 1) { // Stay in state 2 if we received another 0x01.
        state = 1;
      }
    break;
    case 3:
      if ((data >= 'a' && data <= 'z') || (data >= '0' && data <= '9')) {
        hexstring = hexstring + data;
        if (hexstring.length() == 6) {
          state = 4;
        }
      } else if (data == 1) {
        state = 2;
      } else {
        state = 1;
      }
    break;
    case 4:
      if (data == 3) {
        processCommand(command, hexstring);
        state = 1;
      } else if (data == 1) {
        state = 2;
      } else {
        state = 1;
      }
    break;
  }
}

Does the delay(), millis() etc. work on the RFduino?

@Phataas: Not sure, why?

I saw you removed them.

@Phataas: Oh, I just noticed that. I'll add them back in after the analogWrite() calls.


text:
SMlib State Machine Library not working as expected
I have the following setup and sketch.
The problem is that when I click the button it works sometimes, but other times it executes On Off straight after On as if it's executing twice.
This is after pressing the button only 7 times:
Off
On
Off
On
Off
On
Off
On
Off

I thought that was the whole point of a state machine? That it continues to execute the next state (not multiple times at random).
Very very confused with this one.

//http://www.arduino.cc/playground/uploads/Code/FSM.zip
#include <FiniteStateMachine.h>
//http://www.arduino.cc/playground/uploads/Code/Button.zip
#include <Button.h>
//http://www.arduino.cc/playground/uploads/Code/LED.zip
#include <LED.h>

const byte NUMBER_OF_STATES = 2; //how many states are we cycling through?

//initialize states
State On = State(ledOn);
State Off = State(ledOff);

FSM ledStateMachine = FSM(On);     //initialize state machine, start in state: On

Button button = Button(2, INPUT_PULLUP); //initialize the button (wire between pin 12 and ground)
LED led = LED(13);                 //initialize the LED
byte buttonPresses = 0;            //counter variable, hols number of button presses

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

//poor example, but then again; it's just an example
void loop(){
  if (button.uniquePress()){
    //increment buttonPresses and constrain it to [ 0, 1 ]
    buttonPresses = ++buttonPresses % NUMBER_OF_STATES;
    switch (buttonPresses){
      case 0: ledStateMachine.transitionTo(On); Serial.println("On"); break;
      case 1: ledStateMachine.transitionTo(Off); Serial.println("Off"); break;
    }
  }
  ledStateMachine.update();
}

//utility functions
void ledOn(){ led.on(); }
void ledOff(){ led.off(); }
//end utility functions

Maybe you need some sort of debouncing? There's a tutorial on the Arduino site that I think will sort your problem out.

It doesn't look like the state machine is a problem here. More likely it's a problem of the button bouncing, as you don't have any code or circuitry to guard against it.
A button is typically a very simple component which doesn't necessarily make/break connections cleanly. Sometimes it will have a brief intermittent connection, making it look like it's been pressed/released multiple times. This is referred to as bouncing.
There's lots of material online about debouncing, whether in hardware or software. The top answer here may help:

Why does my sketch report too many button presses?


text:
usart sketch uploaded using makefile gives unusual behaviour
This is a simple usart program in avr c which just transmits a character.
#include <avr/io.h>
#include <util/delay.h>
#define F_CPU 16000000UL
#define BAUD 9600
#define BAUD_PRESCALLER ((F_CPU / (BAUD * 16UL)) - 1)
void send_val(unsigned char);
int main() {

UBRR0H = (uint8_t)(BAUD_PRESCALLER>>8);
UBRR0L = (uint8_t)(BAUD_PRESCALLER);
UCSR0B = (1<<TXEN0);
unsigned char x = 'B';
while(1) {

    send_val(x);
    _delay_ms(1000);
}

return 0;
}

void send_val(unsigned char v) {
while(!(UCSR0A & (1<<UDRE0)));
UDR0 = v;

}

when I upload this code via the Arduino IDE, everything is fine and the code works as expected.The LED labeled "L" on the PCB is still.
but, when I upload the code using the following Makefile, the code uploads successfully but the outcome is unexpected. I see a weird character(see EDIT) and the LED "L" blinks a couple of times in that 1 sec delay.
CC=avr-gcc
OBJCOPY=avr-objcopy

CFLAGS=-Os -DF_CPU=16000000UL -mmcu=atmega328p
PORT=/dev/ttyACM0

led.hex: led.elf
    ${OBJCOPY} -O ihex -R .eeprom led.elf led.hex

led.elf: led.o
    ${CC} -o led.elf led.o

install: led.hex
    avrdude -F -V -c arduino -p ATMEGA328P -P ${PORT} -b 115200 -U flash:w:led.hex

I referred the Schematics and the led is connected to SCK but I don't understand why the makefile is causing it to trigger.
that blinking of LED is what I think is causing the issue. Does the IDE have some other specific flags while uploading the code or am I committing some silly mistake?
EDIT: I wrote a small program to see the values in the device node /dev/ttyACM0. the ASCII value of the weired character(looks like a question mark) is actually 255.
another issue I noticed is that when I touch the solder beneath the pin 13 (only pin 13) the led L goes off!
As led L is connected to pin 13 I thought this is some hardware issue with my board but then I uploaded the blink led example code, touched the solder and everything is fine.
what could be the actual issue? this is getting mysterious.

The LED issue is normal and has already been covered here. Short answer: it's powered by an op-amp with an input that is floating unless you pinMode(LED_BUILTIN, OUTPUT);.

The -mmcu=atmega328p compiler flag is needed not only for the compile
phase, but also for the link phase. Otherwise the linker will not know
which CRT (C run time) to link with your program, and it will link none.
The CRT is responsible for things like initializing the stack pointer,
clearing r1 (as required by the AVR calling convention) and calling
your main().
Edit: the following simplified Makefile should work if you have a
modern version of avrdude that understands ELF files:
CC     = avr-gcc
MCU    = atmega328p
CFLAGS = -Os -DF_CPU=16000000UL -mmcu=${MCU}
PORT   = /dev/ttyACM0

led.elf: led.c
    ${CC} ${CFLAGS} $< -o $@

install: led.elf
    avrdude -c arduino -p ${MCU} -P ${PORT} -b 115200 -U $<

Otherwise you can keep your rules for led.elf → led.hex → install.

can you show the exact line I need to add to the makefile. thanks.

using this makefile, the upload succeeded as usual but the issue is still not resolved. I have avrdude version 6.2

@YsK: delete led.elf before typing make, otherwise make will just re-upload the old faulty led.elf.

i noticed that the led still goes off when i touch the solder of pin 13. only for this program..when i try the sample blink program it works fine. is something wrong with my code?

oh sorry, i didn't notice the comment about floating node. thanks for the help


text:
Difficulty connecting arduino ethernet with PC using a switch
Facing difficulty connecting arduino ethernet(w5100) with PC using a switch (Dlink). When both are connected directly(p2p) using ethernet cable, arduino device can be pinged. However, when connected via switch - ping doesn't work, and both devices can't communicate with each other; updated the MAC addr. several times, nothing worked. How can this be resolved?
The same setup works when connected via a router instead of switch. But we need it to work with switch only.
Static ip has been assigned to both PC and arduino uno ethernet shield.

Do all link lights come on?

Yes, three lights are on, one for power, two for the two Ethernet cables.

Have you verified that the switch works?

Yes, pinged two PCs successfully via that switch and cables.

@Alterno, cables are the same.

I think the w5100 works at 10MBs, so is the switch you are using compatible with 10MB/s?

@CodeGorilla Yes, the switch supports that speed.

@user3126972 - Damn.... The only other thing I can think about is there used to be two types of cable, crossed and straight.  You would use a straight cable to go from a device to a switch and a crossed cable to do P2P.  With some modern devices it doesn't matter because they auto-cross.  Its a long shot, but it might be worth checking (Google to work out how to spot the difference).    Could it be related to duplex?  I haven't looked at the datasheet for the W5100.  Does it support full duplex?  Is it supporting full duplex (can you even tell)?

@CodeGorilla, both the cables in use are straight one. Using the same cables I was able to ping two laptops through that switch. Regarding FullDuplex mode - yes, w5100 supports that, google 'W5100_Datasheet_v1_1_6.pdf'

What type of D-link switch is it? Is the switch a managed switch?

Is there an IP conflict? ie. does another device on the network have the same IP address assigned that you have on the PC or Arduino? What does arp -a on the PC say about the Arduino IP address? If there's no IP conflicts, it could be your arp cache on either device isn't being updated. To reset the Arduino, just reboot it. To clear the arp cache on the PC, just do a search for "clear arp cache" along with your OS type (or reboot).


text:
Problems Writing and Clearing 24FC512 EEPROM using Arduino Uno
Solution:
Majenko properly pointed out that I was trying to write across page boundaries and either overwriting or skipping blocks of the EEPROM when I did. This updated write function checks for a page boundary and splits the write into two writes if it is going to write over one.
void writeEEPROMPage(long eeAddress)    {
  int writes = incr;
  bool overflow = false;

  //check for page overrun, adjust writes to fill page and set flag if overrun
  if((eeAddress % 128 + incr) > 127)    {
    writes = 128 - eeAddress % 128;
    overflow = true;
  }
  Wire.beginTransmission(EEPROM_ADR);

  Wire.write((int)(eeAddress >> 8)); // MSB
  Wire.write((int)(eeAddress & 0xFF)); // LSB
  //Write bytes to EEPROM
  Wire.write(rwBuffer, writes); //Write the data
  Wire.endTransmission(); //Send stop condition
  eeAddress += writes;

  if(overflow)  {
    delay(5);
    Wire.beginTransmission(EEPROM_ADR);

    Wire.write((int)(eeAddress >> 8)); // MSB
    Wire.write((int)(eeAddress & 0xFF)); // LSB

    //Write remaining data to new page
    Wire.write(rwBuffer + writes, incr - writes);

    Wire.endTransmission();
    eeAddress += incr - writes;
  }
}

Problem:
I am currently working on a project to record sensor readings to a 24FC512 512kb I2C EEPROM and have been teaching myself to read and write properly to this chip using an Arduino Uno. I am having a problem: when I write too many bytes in one I2C cycle, some bytes of data are skipped and not written.
In theory, I believe I should be able to write up to a 128-byte page to the EEPROM and the buffer in the Arduino Wire library should allow me to write up to 32 bytes (including address) in one transmission without modification. However, when I write more than a certain number of bytes, typically 16, and then read back the data from the EEPROM, I notice that the write commands seem to have skipped part of the write.
For instance, when trying to clear pages of 20 bytes at a time using 0xF0 to fill the space I get this result in the first few lines in blocks of 20:
F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0
F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0
F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0
F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  11  22  33  44  55  66  77  88
+12 lines of F0
F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  55  66  77  88  99  AA  BB  CC
+12 lines of F0
F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  99  AA  BB  CC  DD  EE  FF  00
+5 lines of F0
F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  11  22  33  44  55  66  77  88

The section that has not been cleared matches the original pattern in that location. When I reduce the page size to 16 bytes, the problem goes away and everything is written correctly. The uncleared pattern is also periodic after the first three lines, running 12 lines, error, 12 lines, error, 5 lines, error for the rest of the data. When tried with 30 bytes per transmission, it's periodic by 3-8-3 when organized in lines of 30. In all cases the errors have been at the end of each page of transmission.
This has become very frustrating because I'd like to get the data written to the EEPROM in as little time as possible so I can get a good sensor sample rate (currently 24 bytes per sample) and have time to run other functions. Ideally I'd be able to write every 5 ms to increase the sampling rate to the maximum supported by the EEPROM, so I need to solve this problem.
Here is the code I am using to clear and read the contents of the EEPROM. The variable incr holds the size of the writes I want to make, and pin 12 decides whether the program will read the EEPROM (high) or clear the EEPROM (low). I write data to the EEPROM with the commented out array to run my tests. It is based on example programs for EEPROM from Sparkfun.
#include <Wire.h>

#define EEPROM_ADR 0x54

const int incr = 30;
byte rwBuffer[] = {
  0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
  0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
  0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
  0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0
};

void setup() {
  pinMode(13, OUTPUT);
  pinMode(12, INPUT);
  Wire.begin();
  Wire.setClock(400000);
  long currentSpot = 0;
  if (digitalRead(12)) {
    dumpEEPROM();
  } else {
    while (currentSpot < 64000) {
      writeEEPROMPage(currentSpot);
      currentSpot += incr;
      delay(7);
    }
  }
}

void loop() {
  digitalWrite(13, !digitalRead(13));
  delay(500);
}

void writeEEPROMPage(long eeAddress) {
  Wire.beginTransmission(EEPROM_ADR);
  Wire.write((int)(eeAddress >> 8)); // MSB
  Wire.write((int)(eeAddress & 0xFF)); // LSB
  //Write bytes to EEPROM
  Wire.write(rwBuffer, incr); //Write the data
  Wire.endTransmission(); //Send stop condition
}

void dumpEEPROM() {
  long i;
  int j, readnum, timer = 0;
  Serial.begin(115200);
  timer = millis();
  for (i = 0 ; i < 64000 ; i += incr) {
    //Read all bytes from EERPOM
    readnum = readToBuffer(i);
    for (j = 0; j < incr; j++) {
      if (rwBuffer[j] < 0x10)
        Serial.print("0");
      Serial.print(rwBuffer[j], HEX);
      Serial.print("  ");
    }
    Serial.println();
  }
  timer = millis() - timer;
  Serial.print("Full data dump took ");
  Serial.print((float)timer / 1000, 3);
  Serial.println(" seconds.");
  Serial.end();
}

int readToBuffer(long address) {
  int i = 0;
  Wire.beginTransmission(EEPROM_ADR);
  Wire.write((int)(address >> 8)); // MSB
  Wire.write((int)(address & 0xFF)); // LSB
  Wire.endTransmission();
  Wire.requestFrom(EEPROM_ADR, incr);
  for (i = 0; i < incr && Wire.available(); i++) {
    rwBuffer[i] = Wire.read();
  }
  return i;
}

You are trying to do a page write across a page boundary.

The write control byte, word address and the first data
  byte are transmitted to the 24XX512 in the same way
  as in a byte write. But instead of generating a Stop
  condition, the master transmits up to 127 additional
  bytes, which are temporarily stored in the on-chip page
  buffer and will be written into memory after the master
  has transmitted a Stop condition. After receipt of each
  word, the seven lower Address Pointer bits are internally
  incremented by one. If the master should transmit
  more than 128 bytes prior to generating the Stop condition,
  the address counter will roll over and the previously
  received data will be overwritten. As with the byte
  write operation, once the Stop condition is received, an
  internal write cycle will begin

You are sending blocks of 30 bytes (incr = 30). You have 128 byte pages.

128 / 30 = 4.267 writes per page. The 5th write spans pages. But, in a big bold NOTE in the datasheet:

Page write operations are limited to writing
  bytes within a single physical page,
  regardless of the number of bytes
  actually being written. Physical page
  boundaries start at addresses that are
  integer multiples of the page buffer size (or
  ‘page size’) and end at addresses that are
  integer multiples of [page size – 1]. If a
  Page Write command attempts to write
  across a physical page boundary, the
  result is that the data wraps around to the
  beginning of the current page (overwriting
  data previously stored there), instead of
  being written to the next page as might be
  expected. It is therefore necessary for the
  application software to prevent page write
  operations that would attempt to cross a
  page boundary.

So you write 4 blocks to the first page, then the 5th block fills in the end of the first page then goes back to the start of that page and overwrites what has already been written earlier. Your next page then starts part way through the next block skipping a chunk that you cannot now get to.
You must either do your writes in blocks of an integer division of 128 (so 16 bytes is the largest you can do) or manually detect a page boundary and split your block write into two separate writes - one to finish filling the first page and the next to start filling the next page.

Thank you for correcting my understanding of how pages work and don't work. I'm not sure what I was(n't) thinking when I read that part of the datasheet. I'll update the main post with proper code for handling page boundaries.

Right after each Wire.endTransmission(); you need to insert a delay(5);. The errors you see could be write-related, and/or read related too. You have to let the EEPROM chip process the address request before you start dumping/reading.

I have the line delay(7); in the main program rather than the write function, as I intend to be able to use the writeEEPROMPage function in a program based around a timer interrupt so as to not tie up the processor when it needs to be doing other work.

And you don't have it, at all, for readToBuffer(). It is not only safer, but necessary, to put it right after every Wire.endTransmission();. Try it and see if that influences things. The delay is not optional, and it's there for a reason.

readToBuffer() is reading the EEPROM and to my understanding does not need to wait 5mS to then read or write to the EEPROM.

You seem to know everything and still you come with questions... As I said, try it. You might learn something.


text:
Divide two integers resulting into a float
Suppose I want to divide two integer variables and put the result into a float.
In order to prevent integer division do I have to program like this:
    int i = 6312;
    int j = 258;
    float f;
    f = i;
    f = i/j;

Or can I straightforward program like below and the compiler makes sure it is handled the 'proper' way:
    f = i/j;

why don't you run a test?

Isn't there a typo in your first block of code? Did you mean to write f = f/j;? Otherwise, (a) why bother assigning f = i;? and (b) the last line of the first block is exactly the same as the line in the second block... So the question doesn't make much sense... unless you made a typo...

@Greenonline: you are correct, in the first block of code I should have written f = f/j;

Cast the integers to float before doing the calculation.
float f = float(i) / float(j);

or
float f = (float) i / (float) j;

Always be clear how the calculation should be done, so the compiler will do what you want it to do.

or float f = (float) i / j;

@Juraj, that relies on the compiler to do a float calculation when a float and a int are involved. I prefer to make it clear for someone reading the code and for the compiler what is going on without having to think about it.

As Arduino is C++, you should really use a static cast, to be technically accurate. However, for Arduino code it probably doesn't really matter.
So either
float f = static_cast< float >(i) / static_cast< float >(j);

or
float f = static_cast< float >(i) / j;

Note: Using a static cast on each operand, rather than just one, is  useful to quiet any warnings about the loss of precision with int to float, which typically needs to form a rounded float for large int values.
See C++ int float casting for more info.

Just to add to Jot's answer: Strictly speaking, it should be pointed out that (float) is C, whereas float() is C++.

Also, as you had meant to write in your question:

int i = 6312;
int j = 258;
float f;
f = i;
f = f/j;
Yes, that would work. However, even though it seems quite elegant, it could cause confusion later in time, when someone else examines the code - unless you added a comment explaining why.
it is probably best to keep the code simple and obvious (for debugging purposes) unless you are deliberately intending to obfuscate the code.


text:
How much power can a proto board handle?
I have been working on a project where I will be powering an Arduino and some LED light strips (2 x 3 Meter strips w/ 30 LEDs per meter). I am powering all of it from a 5v 10amp power supply.
Currently I have split the power cable and have it running to the board and the LED's in separate runs.
As I move from a breadboard to a more permanent proto-board, it would be great to add a barrel connector onto the proto-board and just have a single plugin for power so I can easily disconnect it.
Will this cause any issues if all of the power comes from the proto-board? Thanks!

Please provide information about how many LEDs, how long the light strips, and/or the measured current. Your supply can provide 10A, but that has little bearing on what is actually drawn by the system.

@Tyler Pearce What LED strip type are you using?

They are WS2812b/Neopixel strips. 2 x 3 Meter strips w/ 30 LEDs per meter

No, it's not practical do to that with protoboard of any form.
There are two reasons for this:

Barrel jacks are not rated for 10A - I think the most powerful I have seen is 3A.
To handle 10A over (for example) 6 inches of track you would require tracks roughly 8mm wide at 1oz copper. No protoboard provides such tracks.

Even if you're only using half the capacity of your power supply (5A) you still exceed a barrel jack, and would need traces about 3mm wide.

A common way to solve this is to solder a wire onto the tracks on the proto-board.

There is no problem to have your power source coming from your protoboard to supply your arduino since your protoboard can gives to your arduino one of these possibilities explained here.


text:
Weird output from chained 74HC595 shift registers
EDIT 4/2/18: The Arduino tutorial schematics have been corrected! See https://github.com/arduino/Arduino/issues/6433 for that issue.
I have a project where I am trying to load a 16-bit number onto an EEPROM using an Arduino hooked up to two 74HC595 Shift registers.
I'm loosely following this Arduino tutorial: https://www.arduino.cc/en/Tutorial/ShiftOut, but I'm getting unexpected outputs depending on the number I try to load into the register. I've reduced everything to as simple a setup as I can, and have spent several hours trying to figure out what the heck is going wrong... obviously to no avail.
Here is the schematic - with the exception that I moved the capacitor off of ST_CP (why would they put that in the tutorial?) to between power and ground:

Here is my code:
#define SHIFT_DATA 2
#define SHIFT_CLK 3
#define SHIFT_LATCH 4

void setup() {
  pinMode(SHIFT_DATA, OUTPUT);
  pinMode(SHIFT_CLK, OUTPUT);
  pinMode(SHIFT_LATCH, OUTPUT);

  int address = 0b1111111111111111;  // Case 1
//int address = 0b0000000000000000;  // Case 2
//int address = 0b0101010101010101;  // Case 3
//int address = 0b1010101010101010;  // Case 4
//int address = 0b0101100110101110;  // Case 5

  shiftOut(SHIFT_DATA, SHIFT_CLK, MSBFIRST, (address >> 8)); // Load first 8 bits
  shiftOut(SHIFT_DATA, SHIFT_CLK, MSBFIRST, address);        // Load second 8 bits

  digitalWrite(SHIFT_LATCH, LOW);
  digitalWrite(SHIFT_LATCH, HIGH);
  digitalWrite(SHIFT_LATCH, LOW);
}

void loop() {
  // none
}

Here is a picture of my breadboard setup with Case 1 loaded:

And here follows my test cases.

All 1's (1111111111111111). Looks good.
All 0's (0000000000000000). Looks good.
Repeated 01's (0101010101010101). Looks good.
Repeated 10's (1010101010101010). Output: 1010101000000000. First 8 bits match, last 8 are zeros. Huh?
Random sequence (0101100110101110). Output: all over the place. Initially the first 8 bits match as in Case 4, but on repeated resets of the Arduino the output changes, with some weird momentary flickering going on for some of the LEDs. If I press it enough times I can get it back to the initial output, but never what I expect. I am completely stumped. Here is an animated gif of this behavior running on the breadboard: http://i.imgur.com/KEwpSXe.gifv.

What could my problem be? I assume it's something very simple and I'm being an idiot.

One of the other serious (though more subtle) faults with that poor Arduino tutorial is the resistors are too low. Turn on too many LEDs and you draw more current through the 74HC595 chip than it can cope with. You can potentially try and draw up to approx. 109mA with those values but the 74HC595 can only manage 70mA total.

@Majenko If we instead had, say, 40 LEDs and 5 daisy chained shift registers, what resistor and capacitor values would be appropriate to not blow out the shift registers? Thanks!

@JoeFlip The same as for one. Each shift register is a discrete self contained block.

You should change your capacitors.
You only have 0.1µF instead of 1µF for the bulk capacitor (which really wants to be 10µF). In addition you should add 0.1µF (100nF) capacitors directly across the power pins of each chip:

My god, that actually worked. 10 uF across the power rails makes the output rock solid. Shows me how much to trust in a Nano's voltage regulation. Thank you!

It's not the Nano's regulation, it's the internal switching in the '595. The 0.1uF helps with the transient surges.    TPIC6B595 sinking current thru LEDs is also  a much better chip to use here. Shift a 1 in to turn on an output.

I have forum post about the 595 chip and a question and answer about SPI.
You can use SPI to do the transfer. This is faster and simpler than shiftOut. Also you need to bring the latch low before transferring the data.
Simple example sketch:
#include <SPI.h>

const byte LATCH = 10;

void setup ()
{
  SPI.begin ();
}  // end of setup

byte c;
void loop ()
{
  c++;
  digitalWrite (LATCH, LOW);
  SPI.transfer (c);
  digitalWrite (LATCH, HIGH);
  delay (20);
}  // end of loop

Actually not true re the latch - the latch is edge triggered (a simple RS-type flip-flop per bit) and loads the data from the shift register D-type flip-flops into the output latch RS flip-flops on a rising edge. It doesn't matter when it goes low as long as it goes from low to high at the point you want the outputs to change their state. Simple double buffering. True, it doesn't hurt to set it low early like that, but it's not a requirement. The only thing to watch is the minimum LOW or HIGH period of the RCLK (ST_CL on the diagram above) must be more than 20ns at VCC=4.5V.

I thought it was great how you used c as your variable -> c++

I haven't tried your code before heading off to work for the day, but it's worth noting that I don't see a change in behavior by either setting the latch low before shifting out data, or adding a delay(20) before and after each latch change of state.

@sa_leinad Thanks! Unintentional however. :) Scott: I can't reproduce your problem using actual hardware and your original code. However Majenko's suggestion of the 0.1µF capacitors could explain the problem.


text:
GSM library getIPaddress returns local network address 10.X.X.X
I have a Mega board and a GSM shield. I'm using Arduino's example "TestWebServer". The serial monitor shows that the GSM is connected, and returns a IP.
However, the IP is always 10.X.X.X. Isn't that a internal network IP address? How should I get the SIM cards IP? Thanks!

The SIM card does not have an IP address. When the data connection is made to your GSM APN it is assigned an IP in a similar way to DHCP. Often the address is the same after the first connection as the service provider will link that to your SIM for audit purposes. If you setup a private APN then you can arrange to have specific range allocated to your SIM card(s). This is normally only done for security of volume reasons.

I end up using bot.whatismyipaddress.com API to query the external URL address..... Plus just found out that my SIM cannot not work as a web server....


text:
Getting the contacts/ storing contacts to SIM card
I have the GSM shield and is there any ways to get the stored contacts on the SIM card? It seems that the GSM library does not support writing data onto/ reading data from the SIM card?
My aim is to store the SIM card's phone number and some variables onto the SIM card itself, such, I would not need to change the program from time to time.
All I need to do is enter all the variables in the SIM card via any mobile phone (perhaps by storing the variables as contacts, as phone book function should be very common on phones).

What have you researched so far? Following the link you have given for the shield, about the third line of the description is a reference to the AT Command Set used by the chip.
I just did a couple of quick searches through it and found:

2.2.4  ATD><n> Originate phone call to number in memory
3.2.26 AT+CPBF Find phone book entries
3.2.27 AT+CPBR Read current phone book entries
3.2.28 AT+CPBS Select phone book memory storage

probably a good place to start.

Thanks to @Madivad for the AT command inspiration. I am not very familiar with GSM and Arduino. But anyway, the below worked for me.
Credits to @Madivad and people from the arduino forum.
#include <GSM.h>
GSM gsmAccess(true);
int sizer = 200;
char myNumber[200];
int timeout = 5000; // in milli seconds

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

  boolean notConnected = true;

  Serial.println("Connecting to the GSM network");

  while(notConnected){
    if(gsmAccess.begin() == GSM_READY) // Note: I do not require PIN #
      notConnected = false;
    else {
      Serial.println("Not connected, trying again");
      delay(1000);
    }
  }

  Serial.println("Connected");

  theGSM3ShieldV1ModemCore.println("AT+CPBS=\"SM\"");
  int start1 = millis();
  while((millis() - start1) < timeout){
    Serial.print(theGSM3ShieldV1ModemCore.theBuffer().read());
  }
  Serial.print("Set to look at SIM card storage");

  // search for contact name "test"
  theGSM3ShieldV1ModemCore.println("AT+CPBF=\"test\"");
  start1 = 0;
  start1 = millis();
  while((millis() - start1) < timeout && !theGSM3ShieldV1ModemCore.theBuffer().extractSubstring(",\"", "\",", myNumber, sizer)){
    Serial.print(theGSM3ShieldV1ModemCore.theBuffer().read());
  }
  Serial.print("Got contact number");

 // print out the phone of "test"
 Serial.println(myNumber);

}

void loop()
{

}


text:
How do I use the timers on an Arduino Uno R3?
I want to make a simple circuit which returns the time/delay between two, consecutive loud sounds (i.e, a mic reading of ~600) coming from a speaker. I have set up and ADMP 401 microphone for this purpose. How do I measure the time it takes for this application?

Why can't you use millis() for this?

Do you know how to wire up and detect the sound from the microphone using the Arduino?

What is the time precision you need?

@jippie: yes, I have done so successfully

@jfpoilpret: I need time precision of the order of 10^-6 secs. Of course, smaller is better :)

1us precision is about the best you could get on Arduino UNO. But any instruction executed will probably have an impact on that precision. Your best option is probably to use attachInterrupt() but it requires you to first change the electronics so that it converts the mic analog signal to a logical signal (you can use an AOP for that) that is connected to a pin that will trigger the interrupt.

1us may be impossible to reach as it leads to 1MHz frequency; audible sounds are limited to ~20KHz only; I don't even think your mike could react that fast!

Can you elaborate on the mic's analog -> logical signal? And what is an AOP?
IMO, you should post it as an answer instead :)

and ah, good point about the 20 KHz signal. That's where experimentation comes in.

Sorry no time for an answer right now (must go to work...). I'll do it tonight if it's not answered yet. By AOP, I meant op-amp (Operational Amplificator); sorry that was the french abbreviation :-(

You may want to investigate using ICP on timer 1 for lowest possible latency.

Your question is probably not as simple as it may seem.
One approach I would use if I was to address this same problem would consist in:

converting the analog output of the mike into a digital value (based on a threshold to determine)
connect this digital signal to one Arduino pin that can trigger an interrupt when its level changes

Let's first start with the easy part: Arduino program.
Let's say we have a digital signal that raises to 1 as soon as a sound of too high amplitude is captured by the mike; it shall stay 1 as long as the sound does not reduce amplitude enough. We will connect this signal to Arduino pin 3; then we can use attachInterrupt() to have a function called whenever this pon level raises to 1:
volatile static bool started = false;
volatile static unsigned long timing = 0;
volatile static bool finished = false;

void loud() {
    if (started) {
        timing = micros() - timing;
        started = false;
        finished = true;
    } else {
        timing = micros();
        started = true;
        finished = false;
    }
}

void setup() {
    pinMode(3, INPUT);
    attachInterrupt(1, loud, RAISE);
}

void loop() {
    if (finished) {
        // Do something with timing
    }
}

Now the hardest part: electronics!
A first issue we have to deal with is related to the fact that the raw mike signal will have same wave shape as the sound it captures, this wave has a frequency that can vary between 10Hz (bass) and 20KHz (treble).
Indeed, if we convert the mike analog output to a logical value (1 when the analog value is above a threshold we'll call Vt, 0 when it is under Vt) fast enough, then, if the environmental sound as an amplitude above Vt, the logical input connected to your Arduino will oscillate at the same frequency as the sound! This would make our efforts pointless as you would measure the period of the sound wave instead of the elapsed time between two distinct sound bursts.
That means that we should probably first "smoothen" the analog sound signal in order to avoid disturbance of its frequency.
Hence point 1 will have to deal with these 2 aspects:

smoothen analog input value
compare smoothened value with Vt threshold and provide a logical value from this comparison

Comparison can rather easily be performed by an op-amp used as a comparator.
However, the main difficulty you may have with an op-amp is the need for a symetric voltage supply (e.g. +5V/-5V) although it is possible to use a single supply but that raises further limitations (outside the scope of my answer).
Smoothening the signal is potentially more complex, although it can be done with a simple capacitor, because smoothening the signal generally means weakening it, thus you would lose the initial amplitude of the sound signal.
So how can we deal with that?
A Schmitt trigger is probably a good solution for this problem but further experiment will be needed to confirm that.

Thanks for the answer. Well the ADMP 401 already has an amp of sorts, so is a separate op-amp required? Would an op amp like this one work: http://www.protocentral.com/breakout-boards/136-mono-audio-amp-breakout-tpa2005d1.html?search_query=op+amp&results=22 ?

The ADMP 401 uses an Op Amp as a signal amplifier not as a comparator, so you will still need an additional Op Amp mounted as a comparator. There are plenty of Op Amps available and cheap; I think the LM 358 chip (https://www.sparkfun.com/products/9456) should fit your purpose; this one only requires a single supply (between 3V and 32V).

When you mentions "loud sounds (i.e, a mic reading of ~600)" I'm guessing that means you've successfully connected the mic to an ADC input and you are referring to analog readings, right?  (If not you may need to clarify).  I won't worry about scaling or offset biasing the inputs, assuming you have that part down and you can test the Analog input to detect loudness.
If your Arduino can be dedicated to making this measurement (ie: doesn't need to do anything else while doing it), then the simplest solution might be a loop comparing the ADC input with some threshold you have determined, and using micros() to check the time different.  The micros() function has only 4 uS resolution, but the loop time will add more time than that anyway, and actually the limited bandwidth of your audio signals (speaker and mic both) will make any microsecond level measurement suspect anyway.  So the simple loop might be as accurate as you need.
For example:
const int THRESHOLD = 600; // adjust
const int MINDELAY = 1000;  // adjust

long
takeMeasurement() {
    while(analogRead(A4) < THRESHOLD); // wait for first trigger
    long start = micros();
    delayMicroseconds(MINDELAY); // let first noise die down
    while(analogRead(A4) < THRESHOLD); // wait for second trigger
    return micros() - start;
}

You would call this function when you were ready to take a measurement.  To keep the loop time short (when it's waiting for a loud sound), it has no timeout, so it won't return until it does detect two loud sounds.  Depending on your need, you might need to change that and have an escape from the loops.  There are several ways that might be done:

test for micros() exceeding some timeout within the loop
decrement a counter in the loop and exit if it goes to zero (or if the sound is detected)
test a flag (volatile byte) in the loop, which gets set by a timer interrrupt

Which is best depends on other aspects of your overall design.

Yes, that is correct, I'll try this out the next time I start messing with my arduino :)


text:
8-segmet LED's on Adafruit Trinket
I would like to have an array of eight 7- and 8-segment LED numerical displays on my Adafruit Trinket.
I know that there are some prebuilt arrays of 4 LED's. So 2 in array would do just fine.
However, my Adafruit Trinket doesn't have enough ports for that. I have heard something about connecting it to a small piece of controlling hardware that makes me able to have way less ports in need.
What is the appropriate way of connecting a lot of those LED's on only a few ports on a micro controller?
My ideal output would be as follow:
88 88:88:88 or maybe 88 88.88.88
So ideally there would be a small space between the first group of 2 digits and the rest.
Basically, the last 6 digits will represent a time in minutes, seconds and hundreds of seconds.

Do you have to use LED's?  An LCD with a serial interface would be a better match for that board.  You can solve the problem with an I/O expander, but consider simply switching to something built with a full size ATmega328p chip, like one of the mini or micro boards - which would get you both sufficient I/Os and more program resources.

The screen should be visible while the sun is blasting on it. That is why I opted for those. Is there even a better solution for outdoor displays?

Bright sunlight readability is a tough enough requirement that you should pick your specific display first, and then pick a board to drive it.

Do you have a suggestion for a display? I don't have enough knowledge (in fact very little) to be able to pick the correct one.

For LED displays, I advise using a MAX7219.
This circuit:

can manage up to 8 digits (7-segments + 1 LED for DP or colon separator) or up to 64 LEDs
needs only 3 pins to manage display
can be daisy-chained if you need to interface with more than 64 LEDs
requires only 1 resistor to be fully functional
is easily supported on Arduino with this library

I have used it in several circuits and happy with it.
Note that there also other libraries that support this circuit but I haven't used them.
This circuit has only one downside: its price (about $10 each); but the price is counter-balanced by its simplicity and the fact you don't need any additional component (e.g. transistors) besides a simple resistor.

Wow thanks for this answer! I will look into it this weekend. Looks perfect for what I need!


text:
Seeing consistent serial data loss over USB, have ruled out hardware and rx/tx software. What's left?
I have a Lasersaur, which is an arduino-based open-source laser cutter. Part of its capabilities is raster engraving, where you etch images based on pixel data, rather than vector data. Recently I started experiencing a weird issue where I am losing some of the data that I am sending over serial to the machine, and the end of the image gets cut off. I don't believe those details are relevant to this question, but you can read my posts here for more info.
Basically, on my old Laptop B, engraving works. If I use the exact same USB hardware connection, firmware, frontend software executable, engraving settings, and image file on my current Laptop A, I see bad results. The last ~20 pixels or so of each image line are not etched in, and the only reason I can think for this is that the color data for these pixels were not sent in the first place. Notably, Laptop A used to work a few months ago when I last tried this out. So I'm pretty confident that I've ruled out hardware and rx/tx software as the possible issues.
The only difference between the two machines that I can think of that has changed since then is that I installed the Windows 10 1909 update, as well as some other software that I would have to dig back through to list out. I'd really like to not do a fresh Windows reinstall on my primary machine, but I'm close to that point.
Could something there be causing an issue? I'm out of my depth at this point, and don't know how either the operating system or another program could be affecting serial data transfer, and wouldn't know the first way to narrow it down.
Some more thoughts which may or may not be important:

There does not seem to be data corruption, only data loss. The rx/tx protocol implements some error detection (sends every byte twice and checks for equality), and I am not seeing error corruption messages that would pop out if that were the case.
There does not seem to be any randomness. The same behavior happens for images of different widths (leading me to think that the tx buffer isn't filling up), is the same for each image line, and has always been consistent.
The Arduino in the machine is an Arduino Uno R3. Compilation is done using the Arduino compiler on some custom C code (not though the IDE).

Do you know in which format data is sent to the arduino, does it transmit the whole image, separate lines or seperat pixels? I also suspect buffer problems. Can you print what ever is received by the atmega? Generally I don't believe that a windows reinstallation would help

It's a custom protocol, wherein bytes from 0-127 are message flags and 128-255 are data. The image is broken up into a list of horizontal lines. The laptop sends configuration data (power level, pixel size in mm, travel speed, etc), then the starting and ending coordinates of each raster line, then a stream of bytes that has a grayscale value for each pixel. This repeats one line at a time, so the image isn't being sent at once. For the test image I'm using, there are about 400 pixels in each line but I've used test images with ~5000 pixels in each line and it's still only the last 20 or ...

Are you sure that your new laptop causes the problem (be it the different OS or what ever) and that there hasn't been a firmware change since you last tried successfully? Simple test: connect tx to rx on the pc side and compare if the frontend sw sends what it's supposed to send.

... so which are cut out. Which doesn't mean it's not a buffer error, but it hints to me that it's not something obvious like the buffer filling. I could be wrong.
Since the code flashed to the Atmega isn't done through the arduino IDE, it wouldn't be an easy process to echo back what its receiving, but I could do it.

I'm sure it's specific to the laptop and not the atmega firmware, I had the two laptops side by side last night and was swapping the USB cable between them (with restarts, not just hotswapping, so that wouldn't have been the issue).
Plugging the rx line back into the tx machine and reading it out is a good idea... maybe I'll google around to try and figure out how to do that. The frontend software has a debug terminal that spits out what it thinks it's sending, so I could compare against what it actually is. I still don't know what I would do to fix it if they were different though.

To further investigate, what exactly is being send, you could use another Arduino/microcontroller and let it snoop on the PCs TX line.

As an alternative to @chrisl's proposal (that is a good one!) you could change the Arduino's code to count the received bytes and show them in some appropriate way. What OS is your laptop B running on?

Laptop B is running Windows 10 version 1803. Laptop A was working when I tested it out a few months ago on Windows 10 version 1903.

I have solved the bug, you can see the writeup on the Lasersaur google group. The short of it was that this was a software bug, which was only being triggered when the hardware conspired to have some timing delays. I'm still unclear why the behavior was inconsistent previously - I must have been on the borderline of the data delays causing an issue or not.

The driver board for your "Lasersaur" appears to be based around the Adafruit Trinket Pro.
That board, on Adafruit's website, is deprecated, with the following warning:

Deprecation Warning: The Pro Trinket bit-bang USB technique it uses doesn't work as well as it did in 2014, many modern computers won't work well. So while we still carry the Pro Trinket so that people can maintain some older projets, we no longer recommend it.

So basically the USB interface is naff. It's too slow to keep up with modern computers (hence your old laptop works but your new one doesn't), and you lose data.
You should look into the possibility of upgrading the controller board to something a little more modern and capable.

For UNO R3 based boards there is another fundamental flaw: there is a 64 byte receive buffer and no flow control.  That means if you send data too fast - faster than the board can process it - data will be lost.

Hmm, did more digging and it looks like the board that's supposed to be in the machine is an Arduino Uno R3. I'll pop off the lid when I get home today to check, but could you point me towards where you saw that info?
My understanding was that if I'm communicating at the correct baudrate there shouldn't be a thing as "sending too fast", but I could be wrong there. Maybe I could try artificially slowing down the transmission rate...

Which? What the device should be, or the deprecation warning?

What the device should be, I was able to find the deprecation warning.

@Scott That was the result of a lot of digging. The manual led me to a GitHub repo. In there was a bill of materials. In that was a link to a fritzing file for the pcb. In that was the trinket.

Today I learned about fritzing. I assume this was the repo? https://github.com/nortd/driveboard/tree/master/DriveboardUSB
Thanks! You've given me a lot to go track down.

I don't believe that's the specific issue, I digged through the frizting file and didn't see anything related to a Trinket Pro, so I popped open the electronics box and the only microcontroller in there is the one on the Uno R3.
To slow things down I tried cutting the baudrate in half, but that doesn't seem to have changed the results. Still dead in the water over here, I think reinstalling windows and keeping my fingers crossed is the only step I can think of.

Well, I was able to resolve it, but I’m not sure how. After going through the steps I’ve outlined in my replies to answers here, I tried buying a new Arduino Uno R3, but that didn’t fix anything either. My last step was to do a Windows “Reset” which reinstalls Windows while keeping files but resets settings and programs. After reinstalling and adding back in all the programs I originally had, the serial communication worked again. I really don’t have a good explanation as to why this worked, but at least it did.
Edit: This problem reappeared, and the windows reset did not fix the issue this time.


text:
Why is int only 2 bytes?
When using C/C++ on other platforms, the int type is typically 4 bytes (or potentially more). However, on Arduino, it's only 2 bytes.
Why is it different? Does it affect performance if I always use the 4 byte long instead?

note that int is 4 bytes on the Arduino Due. A short will be 2 byte on all existing Ardunios, but I emphasize the others' advice to use int16_t or uint16_t.

The ATmega328 used in a lot of Arduinos is a 8-bit microcontroller. This means that registers are 8-bits, the data bus is 8-bits, the ports are 8-bits. There are some minimal 16-bit aspects to the system (e.g. one of the timers), but nearly everything is 8-bits.
Therefore, most operations handle 8-bits at a time. Working on anything except 8-bits (i.e. 16-bit or 32-bit integers and floating point numbers) requires what could essentially be described as software emulation, where the compiler uses multiple instructions to work on these larger variables.
8-bits is obviously adequate to address a 8-bit port. It's also enough to deal with many loop counters, return values, and ASCII characters. It isn't really enough though when dealing with numbers. A signed 8-bit int (int8_t) can only represent -128 -> +127. Unsigned (uint8_t) can only represent 0 -> 255.
8-bit integers are quite limiting. C/C++ int must represent at least -32,678 -> +32,767 so maps to int16_t - the smallest size that will do so. This gives a good balance of range and efficiency. This is especially important when beginners are learning - overflow is not really something that non-programmers understand.
There is a performance impact of doing this however, because most 16-bit operations take at least twice as long as an 8-bit operation, and use twice as many registers. This may or may not make a difference to you.
Many of us switch to the native types such as int8_t and uint8_t as it gives you far more control.

Just a note: it's not the Arduino Team that mapped int to int16_t, "int" is a C/C++ reserved keyword, and the type mapping is part of the ABI (http://gcc.gnu.org/wiki/avr-gcc) that the avr-gcc compiler's developers decided to follow. Another notably difference is in the "double" type that usually is 64bit wide, while in the avr-gcc is 32bit like "float"

Thanks. Not sure why I wrote that. I know int must represent 32,678 -> +32,767 (though, actually, I think there was a proprietary compiler for one of the NEC processors that didn't follow this). I think it is because I don't like hiding widths on embedded systems - using int16_t is much clearer.

+1 for the use of clear native types! On the Arduino Due, an int is 32-bit! http://arduino.cc/en/Reference/int

One important fact about C and C++ languages is that their respective standards do not define the size (in bytes) of integral and floating point number types.
They just define minimal ranges and relation between these ranges, e.g.
range(short) <= range(int) < range(long)

So the size of e.g. an int will typically depend on:

the target platform (processor)
the compiler itself

are you saying sizeof(short) == sizeof(int) == sizeof(long) is possible?

@ron-e Theoretically, yes, that would be possible. In practice, however, I've never seen that. In most compiler/platforms, one could expect (although it is not imposed) that sizeof(short) < sizeof(long).


text:
ESP8266 as ISP program for ATMega16
I have used below program for ESP8266 as ISP to upload a program to an ATmega16.
ISP program uploaded in ESP8266
#include <SPI.h>
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <ESP8266AVRISP.h>

const uint8_t reset_pin = 5;
const uint16_t port = 328;

ESP8266AVRISP avrprog(port, reset_pin);

void setup() {
    Serial.begin(9600);//115200
    Serial.println("");
    Serial.println("Arduino AVR-ISP over TCP");
    avrprog.setReset(false); // let the AVR run

    // listen for avrdudes
    avrprog.begin();
}

void loop() {
    static AVRISPState_t last_state = AVRISP_STATE_IDLE;
    AVRISPState_t new_state = avrprog.update();
    if (last_state != new_state) {
        switch (new_state) {
            case AVRISP_STATE_IDLE: {
                Serial.printf("[AVRISP] now idle\r\n");
                Serial.println("idle...");
                // Use the SPI bus for other purposes
                break;
            }
            case AVRISP_STATE_PENDING: {
                Serial.printf("[AVRISP] connection pending\r\n");
                Serial.println("pending...");
                // Clean up your other purposes and prepare for programming mode
                break;
            }
            case AVRISP_STATE_ACTIVE: {
                Serial.printf("[AVRISP] programming mode\r\n");
                Serial.println("Active...");
                // Stand by for completion
                break;
            }
        }
        last_state = new_state;
    }else{
      Serial.println("newstate not equal to old");
    }
    // Serve the client
    if (last_state != AVRISP_STATE_IDLE) {
        avrprog.serve();
        Serial.println("serve..");
    }
}

Then I have changed the board to ATmega16 and used programmer as AVR ISP and fetched/written below simple blink program to upload in ATmega16.
void setup() {
  // initialize digital pin 13 as an output.
  pinMode(1, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(1, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);              // wait for a second
  Serial.println("light on");
  digitalWrite(1, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);              // wait for a second
  Serial.println("light off...");
}

Tried uploading blink program to ATmega16 using ESP8266 as ISP by Sketch =>Upload Using Programmer. This resulted to compilation followed by uploading status in Arduino IDE for longer period. I didn't get any response after 10 mins of time. Then i have tried opening Serial Monitor which shows newstate not equal to old.
I am not sure what went wrong in my coding? How can I debug this issue ?

I have been never sucessfull with the ISP Project. C:\avrdude-5.4-win>avrdude -c arduino -p m2560 -P net:192.168.178.38:328 -u -F
avrdude: ser_drain(): read error: Falscher Parameter. avrdude: ser_drain(): read error: Falscher Parameter. avrdude: ser_drain(): read error: Falscher Parameter. avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x14 avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x10
avrdude: stk500_initialize(): (b) protocol error, expect=0x10, resp=0x01
avrdude: initialization failed, rc=-1
avrdude: AVR device initialized and ready to accept instr

1. Uploading the sketch to your ESP8266

Tools > Board > select the appropriate ESP8266 board
File > Examples > ESP8266AVRISP > Arduino_Wifi_AVRISP
Change lines 7 and 8 to match the SSID and password of your WiFi router
Sketch > Upload
After the upload completes unplug the ESP8266 from your computer.

2. Generating the .hex file and the upload command

Open the sketch you want to upload to your ATmega16
Tools > Board > ATmega16
File > Preferences > Show verbose output during: > upload (check)
Sketch > Upload
The sketch will compile and then the upload will fail. This is the expected behavior. The goal of this process is to generate the .hex file that will be uploaded and the correct upload command.
Scroll the black console window at the bottom of the Arduino IDE window up until you see a line that looks something like:

>
E:\Arduino\hardware\tools\avr/bin/avrdude -CE:\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM54 -b115200 -D -Uflash:w:C:\Users\per\AppData\Local\Temp\arduino_build_288143/Blink.ino.hex:i

3. Connecting the ESP8266 to the ATmega16
Connect the ESP8266 to your ATmega16 board as follows:
+----------+-----------+
| ESP8266  | ATmega16  |
+----------+-----------+
| GPIO12   | MISO      |
| GPIO13   | MOSI      |
| GPIO14   | SCK       |
| GPIO5    | RESET     |
+----------+-----------+

You also need to power the ATmega16. It is recommended to use 3.3 V since this is what the ESP8266 is running at. Make sure the ground of the ESP8266 is connected to the ground of the ATmega16.
4. Starting the ESP8266AVRISP

Plug the ESP8266's USB cable back in to your computer
Tools > Serial Monitor
Select 115200 from the baud rate menu in the bottom right corner of Serial Monitor
You should see something like

IP address: 192.168.0.100
  Use your avrdude: avrdude -c arduino -p  -P net:192.168.0.100:3000 -t # or -U ...

5. Uploading via ESP8266AVRISP

The second line you saw in the Serial Monitor in step 4 is the sketch's attempt to give you the AVRDUDE command you need to run to upload to your ATmega16 via the ESP8266AVRISP. Unfortunately they got a bit vague at the end. Apparently they are trying to steer you towards using AVRDUDE in terminal mode via the -t option but also mentioning that -U might be preferred. I recommend the latter since the Arduino IDE has helpfully generated the -U command for you already.
Since you need to run a custom AVRDUDE command to upload to your ATmega16 over the network you will not be able to do the upload via the Arduino IDE. Start the command line on your computer.
Now you need to merge the upload command you generated when you did the intentionally failed upload to the ATmega16 in step 2 with the command that was printed to Serial Monitor in step 4. In my examples, this merged command would be:

>
E:\Arduino\hardware\tools\avr/bin/avrdude -CE:\Arduino\hardware\tools\avr/etc/avrdude.conf -v -c arduino -p atmega16 -P net:192.168.0.100:3000 -Uflash:w:C:\Users\per\AppData\Local\Temp\arduino_build_288143/Blink.ino.hex:i

Your command will be similar to mine but the path to avrdude, avrdude.conf, the IP address, port, and path to the .hex file will be different. Enter your merged AVRDUDE command at the command line.
The upload should now proceed successfully.

Comments
The above is quite a complex process. Although it will be significantly easier with subsequent uploads, it will likely still not be as easy as an upload via the Arduino IDE. I would not recommend regularly using the ESP8266 as an AVR ISP simply because it's what you have on hand. Instead I would strongly recommend you to just buy a cheap (~$3 USD with free shipping from China) 6 pin USBasp from eBay.
The primary benefit of using the ESP8266 for this application is that it can be done over the WiFi network rather than the traditional USB connection but it's questionable how often that will truly be useful.

Followed all the procedures and received below output when I run avrdude command. ser_drain(): read error: The parameter is incorrect. stk500_disable(): protocol error, expect=0x14, resp=0x10 stk500_initialize(): (b) protocol error, expect=0x10, resp=0x01 Mentioned complete error list in my question.

You just saved my cheap Digispark-Attiny85 clone that I previously messed up... An ESP8266 was all I had around. This worked perfectly. Thanks!