text:
Buffer reverse to string
A few hours since I started messing with my first Arduino and I was trying to understand a small program and need some help. The program sends out the MAC address to the serial port. As it's little endian, the "printBufferReverse" reverses the buffer as shown below. But instead of sending this data to the serial port, how do I store the same data into a string variable? Thanks so much
#include <bluefruit.h>
void scan_callback(ble_gap_evt_adv_report_t* report)
{
  uint8_t len = 0;
  uint8_t buffer[32];
  memset(buffer, 0, sizeof(buffer));

  // MAC is in little endian --> print reverse
  // NOTE: I want to store this into a string variable
  // NOTE: the reversing
  Serial.printBufferReverse(report->peer_addr.addr, 6, ':');
  Serial.print("\n");

  /* TX Power Level */
  if (Bluefruit.Scanner.parseReportByType(report,
    BLE_GAP_AD_TYPE_TX_POWER_LEVEL, buffer, sizeof(buffer)))
    {
      Serial.printf("%14s %i\n", "TX PWR LEVEL", buffer[0]);
      memset(buffer, 0, sizeof(buffer));
    }
}

And the below line how do I store the data to a string instead of sending to serial port? It's adding a hypen to make the end result look like this:12-09-69-57-45-45-43-41-52-45-20
Serial.printBuffer(report->data, report->dlen, '-');

I don't want to send this to serial port but to store in a string variable.
This is the board that I am using: https://www.adafruit.com/product/3406
Complete code
/*********************************************************************
 This is an example for our nRF52 based Bluefruit LE modules

 Pick one up today in the adafruit shop!

 Adafruit invests time and resources providing this open source code,
 please support Adafruit and open-source hardware by purchasing
 products from Adafruit!

 MIT license, check LICENSE for more information
 All text above, and the splash screen below must be included in
 any redistribution
*********************************************************************/

#include <bluefruit.h>

/* For a list of EIR data types see:
 *    https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile
 *    Matching enum: cores/nRF5/SDK/components/softdevice/s132/headers/ble_gap.h */

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

  Serial.println("Scanning for beacons");
  Serial.println("------------------------------------\n");

  // Initialize Bluefruit with maximum connections as Peripheral = 0, Central = 1
  // SRAM usage required by SoftDevice will increase dramatically with number of connections
  Bluefruit.begin(0, 1);

  // Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
  Bluefruit.setTxPower(4);

  /* Set the device name */
  Bluefruit.setName("Bluefruit52");

  /* Set the LED interval for blinky pattern on BLUE LED */
  Bluefruit.setConnLedInterval(250);

  /* Start Central Scanning
   * - Enable auto scan if disconnected
   * - Filter out packet with a min rssi
   * - Interval = 100 ms, window = 50 ms
   * - Use active scan (used to retrieve the optional scan response adv packet)
   * - Start(0) = will scan forever since no timeout is given
   */
  Bluefruit.Scanner.setRxCallback(scan_callback);
  Bluefruit.Scanner.restartOnDisconnect(true);
  Bluefruit.Scanner.filterRssi(-80);
  //Bluefruit.Scanner.filterUuid(BLEUART_UUID_SERVICE); // only invoke callback if detect bleuart service
  Bluefruit.Scanner.setInterval(160, 80);       // in units of 0.625 ms
  Bluefruit.Scanner.useActiveScan(true);        // Request scan response data
  Bluefruit.Scanner.start(0);                   // 0 = Don't stop scanning after n seconds

  Serial.println("Started ...");
}

void scan_callback(ble_gap_evt_adv_report_t* report)
{
  uint8_t len = 0;
  uint8_t buffer[32];
  memset(buffer, 0, sizeof(buffer));
  boolean hasPayload;
  String bleDvcID;
  String advPayload;

  hasPayload = false;
  bleDvcID = "";
  advPayload = "";

  /* Display the timestamp and device address */
  /*
  if (report->scan_rsp)
  {
    Serial.printf("[SR%10d] Packet received from ", millis());
  }
  else
  {
    Serial.printf("[ADV%9d] Packet received from ", millis());
  }
  */
  // MAC is in little endian --> print reverse
  // bleDvcID = printBufferReverse(report->peer_addr.addr, 6, ':');
  // char buffer[18] = "";
  /*
    snprintf(buffer, "%02X-%02X-%02X-%02X-%02X-%02X", 18,
        report->peer_addr.addr[5],
        report->peer_addr.addr[4],
        report->peer_addr.addr[3],
        report->peer_addr.addr[2],
        report->peer_addr.addr[1],
        report->peer_addr.addr[0]
    );
   */
  Serial.printBufferReverse(report->peer_addr.addr, 6, ':');
  Serial.print("\n");

  /* Raw buffer contents */
  Serial.printf("%14s %d bytes\n", "PAYLOAD", report->dlen);
  if (report->dlen)
  {
    hasPayload = true;
    Serial.printf("%15s", " ");
    Serial.printBuffer(report->data, report->dlen, '-');
    Serial.println();
  }

  /* RSSI value */
  Serial.printf("%14s %d dBm\n", "RSSI", report->rssi);

  /* Complete Local Name */
  if(Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_COMPLETE_LOCAL_NAME, buffer, sizeof(buffer)))
  {
    Serial.printf("%14s %s\n", "COMPLETE NAME", buffer);
    if (strcmp((const char*)buffer, "Temperature Fren")==0)
    {
        Serial.println("Found beacon!");
    }
    memset(buffer, 0, sizeof(buffer));
  }

  /* TX Power Level */
  if (Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_TX_POWER_LEVEL, buffer, sizeof(buffer)))
  {
    Serial.printf("%14s %i\n", "TX PWR LEVEL", buffer[0]);
    memset(buffer, 0, sizeof(buffer));
  }

  /* Check for UUID16 Complete List */
  len = Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_COMPLETE, buffer, sizeof(buffer));
  if ( len )
  {
    printUuid16List(buffer, len);
  }

  /* Check for UUID16 More Available List */
  len = Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_MORE_AVAILABLE, buffer, sizeof(buffer));
  if ( len )
  {
    printUuid16List(buffer, len);
  }

  /* Check for UUID128 Complete List */
  len = Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_128BIT_SERVICE_UUID_COMPLETE, buffer, sizeof(buffer));
  if ( len )
  {
    printUuid128List(buffer, len);
  }

  /* Check for UUID128 More Available List */
  len = Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_128BIT_SERVICE_UUID_MORE_AVAILABLE, buffer, sizeof(buffer));
  if ( len )
  {
    printUuid128List(buffer, len);
  }

  /* Check for BLE UART UUID */
  /*
  if ( Bluefruit.Scanner.checkReportForUuid(report, BLEUART_UUID_SERVICE) )
  {
    Serial.printf("%14s %s\n", "BLE UART", "UUID Found!");
  }
  */
  /* Check for DIS UUID */
  /*
  if ( Bluefruit.Scanner.checkReportForUuid(report, UUID16_SVC_DEVICE_INFORMATION) )
  {
    Serial.printf("%14s %s\n", "DIS", "UUID Found!");
  }
  */
  /* Check for Manufacturer Specific Data */
  /*
  len = Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_MANUFACTURER_SPECIFIC_DATA, buffer, sizeof(buffer));
  if (len)
  {
    Serial.printf("%14s ", "MAN SPEC DATA");
    Serial.printBuffer(buffer, len, '-');
    Serial.println();
    memset(buffer, 0, sizeof(buffer));
  }
  */
  Serial.println();
}

void printUuid16List(uint8_t* buffer, uint8_t len)
{
  /* Serial.printf("%14s %s", "16-Bit UUID"); */
  for(int i=0; i<len; i+=2)
  {
    uint16_t uuid16;
    memcpy(&uuid16, buffer+i, 2);
    /* Serial.printf("%04X ", uuid16); */
  }
  /* Serial.println(); */
}

void printUuid128List(uint8_t* buffer, uint8_t len)
{
  (void) len;
  /* Serial.printf("%14s %s", "128-Bit UUID"); */

  // Print reversed order
  for(int i=0; i<16; i++)
  {
    const char* fm = (i==4 || i==6 || i==8 || i==10) ? "-%02X" : "%02X";
    /* Serial.printf(fm, buffer[15-i]); */
  }

  /* Serial.println(); */
}

void loop()
{
  // Toggle both LEDs every 1 second
  digitalToggle(LED_RED);

  delay(1000);
}

Please edit your question to state which Arduino board you're compiling for. I believe Serial.printBufferReverse() is only part of the Adafruit nRF52 core, and even that only added recently so many people here may not be familiar with it.

Sorry I was supposed to mention that I am using Arduino IDE to program Adafruit nRF52 board. But the question itself isn't tied strictly to a particular board.

You can do it with snprintf_P:
char mac[18];

snprintf_P(mac, 18, (PGM_P)F("%02X-%02X-%02X-%02X-%02X-%02X"),
    report->peer_addr.addr[5],
    report->peer_addr.addr[4],
    report->peer_addr.addr[3],
    report->peer_addr.addr[2],
    report->peer_addr.addr[1],
    report->peer_addr.addr[0]
);

That is, assuming that report->peer_addr.addr is an array of 6 bytes.
If your strange board doesn't support the _P variants of string manipulation functions then you can drop that part along with the (PGM_P)F(...) bit:
char mac[18];

snprintf(mac, 18, "%02X-%02X-%02X-%02X-%02X-%02X",
    report->peer_addr.addr[5],
    report->peer_addr.addr[4],
    report->peer_addr.addr[3],
    report->peer_addr.addr[2],
    report->peer_addr.addr[1],
    report->peer_addr.addr[0]
);

Doing so on an Ardunio, though, would waste RAM.

Thanks. The first one with _P does not exist. And the 2nd one snprintf throws the following error; invalid conversion from 'uint8_t* {aka unsigned char*}' to 'char*' [-fpermissive]. Btw this is the board: https://www.adafruit.com/product/3406

@M.M, please add the reference about the board to your question

@jsotola sure, done.

@Majenko, the 2nd function seems to help but I get this error; conflicting declaration 'char buffer [18]'

So choose another name that doesn't conflict with whatever is in the rest of your sketch.

Choose another name? Can I know for which one to choose another name? The only other things that I have in the sketch are                                       #include <bluefruit.h>
void scan_callback(ble_gap_evt_adv_report_t* report)
{
uint8_t len = 0;
uint8_t buffer[32];
memset(buffer, 0, sizeof(buffer));

So your buffer variable is doing nothing then? So delete it. But first engage brain.

buffer is used elsewhere. I have edited my question to add that.

So pick a new name for your Mac variable. Maybe mac would be a good choice.

Even if I put the "snprintf" code that you provided in a new sketch, I get an error; invalid conversion from 'const char*' to 'size_t {aka unsigned int}' [-fpermissive] ... apologies but it's only been a few hours using Arduino IDE and C++. Yet to get a hang of things.

Hang on, seems I got the parameters in the wrong order. Check the new version of the code.

@Majenko, cool! Yup, that was it. Thanks a zillion. One tiny part left; how do I get this into a string? Serial.printBuffer(report->data, report->dlen, '-'); cos this is dynamic buffer

You will have to do it peacemeal and strcat each chunk.

Okay. Thank you so much. I'll figure the remaining part out.

I have a blog post that may help you out: https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/

wow, that is cool! Appreciate your help so much. Cheers


text:
Get ESP32 Chip ID into a string variable (Arduino/C++ newbie here)
It's just a few days since I started using Arduino IDE ( programming an ESP32 ). As I learn, I am trying to write some snippets. I wanted to store the Chip ID of ESP32 into a variable (preferably string?) so that I can generate an unique device name. I looked through the ESP32 example programs and came across this program which just prints the Chip ID to the serial console.
  uint64_t chipid;

  chipid = ESP.getEfuseMac(); //The chip ID is essentially its MAC address(length: 6 bytes).
  Serial.printf("ESP32 Chip ID = %04X", (uint16_t)(chipid >> 32)); //print High 2 bytes
  Serial.printf("%08X\n", (uint32_t)chipid); //print Low 4bytes.

Now this works fine but I needed to store it into a variable in the following format "ESP32-0A1B3C4D5E6F" ( the last part of which is the Chip/MAC ID which is 6 bytes ). I went about some reading and currently reading and managed to get this far
  char ssid1[15];
  char ssid2[15];

  uint64_t chipid = ESP.getEfuseMac(); // The chip ID is essentially its MAC address(length: 6 bytes).
  uint16_t chip = (uint16_t)(chipid >> 32);

  snprintf(ssid1, 15, "%04X", chip);
  snprintf(ssid2, 15, "%08X", (uint32_t)chipid);

  Serial.print(ssid1);
  Serial.println(ssid2);

I am trying to read this which seems to be an excellent article on handling Arduino strings but just being a few days old with Arduino/c++ I am having some difficulty in wrapping my head around some of the concepts. I come from a Python, PHP, Javascript background so I guess this is gona take a little bit of a time. I am getting the output that I want in the serial console but now I would need this in this format (MCUDEVICE-0A1B3C4D5E6F). I am sure this code can be written in a much nicer, cleaner manner but for now I need this to proceed with another snippet (which relies on device name in the above mentioned format). Can anyone provide some pointers while I try check out the different ways I could achieve this? I just want to be sure that I am not writing ugly (and dangerous code - crashes, buffer overruns etc). Greatly appreciate any pointers. I guess I am starting to get a little paranoid about handling strings ( especially on low memory devices like typical mcus ).

What is the purpose of the following line: uint16_t chip = (uint16_t)(chipid >> 32); ? Thanks

@ItamarVieira this copies the highest 16 bits from “chipid” (which is a 48-bit value in a 64-bit variable) to the “chip” variable (which is a 16-bit variable).

You can combine all your work into one single line with the snprintf. You aren't limited to just one variable, and you can add plain text:
char ssid[23];

snprintf(ssid, 23, "MCUDEVICE-%04X%08X", chip, (uint32_t)chipid);

Why don't you simply use:
char ssid[23];
snprintf(ssid, 23, "MCUDEVICE-%llX", ESP.getEfuseMac());

This way no need to bit-shift and extra middle variables...
Just watch out for capital X for uppercase result and small 'l' for type indication. (meaning use either llX or llx and not LLX).

This works on an ESP32-S3 WROOM  on Arduino 1.8.19:
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);

  String MCUtype = "ESP32s3" ;
  char ssid[14];
  snprintf(ssid, 14, "%llX", ESP.getEfuseMac());
  Serial.println(ssid); //
  String ssid1 = ssid ; // convert from char to String
  Serial.println(ssid1);
  int StrLen = ssid1.length();
  Serial.printf("Length of the string %i characters \r\n",StrLen);
  String MAC ="";
  int i = 0; while ( i < 6) {
    MAC = MAC + ssid1.substring(StrLen-2-2*i,StrLen-2*i)+":";
    i++ ;
  }
  MAC = MAC.substring(0,17); // remove last :
  Serial.println(MAC);
  String Serialnumber = MCUtype+"-" ;
    int j = 3; while ( j < 6) {
  Serialnumber = Serialnumber + ssid1.substring(StrLen-2-2*j,StrLen-2*j);
  j++ ;
  }
  Serial.println(Serialnumber);
}

void loop() {
  // put your main code here, to run repeatedly:

}

source: Stack Exchange

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

sort: votes


text:
bit_is_clear(ACSR, ACO) Instead of digital_read(1)==LOW
I am attempting to create a program for the atmega328P which will enable the aux input of a Toyota Corolla stereo. In order to do this, I'm bitbanging AVC LAN. Nearly all of my research comes from this site:
https://github.com/halleysfifthinc/Toyota-AVC-LAN
In this example, Frigon has wired his Atmega8 in a peculiar way. Instead of connecting the + terminal directly to a single pin of his Atmega8, he's connected it to a pulldown resistor, resisted it to the - terminal (presumably for bus termination) and a digital pin as well as an analog pin. The - terminal has been given similar strange treatment.
In his function ReadBits(), he waits for a physical 1, then sets a timer and waits for a physical 0 to measure the length of the pulse. But when he does this, he uses the equivalent of
while ( bit_is_clear( ACSR, ACO ) );

That's completely Greek to me. Does this have something to do with something called in Internal Analog Comparator?
I attempted to create something similar using
while( digitalRead( 2 ) );

but I'm reading static as well as honest-to-goodness pulses. I assume that, anyways, because I'm getting pulses of length 2-7 ticks when many are closer to 20-40 ticks (measured using TCNT0 with no custom prescaler).
So... what exactly is he doing with ACSR and ACO? Why is his + and - terminals connected to more than one pin? Why are his diodes there?
=========================EDIT=======================
Following Edgar's advice, I've reworked my schematic and code to closely match Frigon's work. Below is my code:
#include <avr/wdt.h>

#define fwVer       "v0.1"
#define fwDt        __DATE__
#define DATAPIN     2

//====================================================================================COPYPASTED
#define DATAIN_PIN              ACSR
#define DATAIN                  ACO

#define INPUT_IS_SET            ( bit_is_set( DATAIN_PIN, DATAIN ) )
#define INPUT_IS_CLEAR          ( bit_is_clear( DATAIN_PIN, DATAIN ) )
//===================================================================================WHAT DOES THIS MEAN

byte data[255];

void setup() {
  LedOff();

  Serial.begin(9600);

  pinMode(3,OUTPUT);
  pinMode(2,OUTPUT);
  digitalWrite(3,HIGH); //"leave the pins tri-stated" according to Frigon
  digitalWrite(2,LOW);
  pinMode(LED_BUILTIN,OUTPUT);

  //two second watchdog
  wdt_enable( WDTO_2S );

  Serial.println("Firmware "+String(fwVer)+", compiled on "+fwDt);
  LedOff();
}

void LedOff() {
  digitalWrite(LED_BUILTIN, LOW);
}
void LedOn() {
  digitalWrite(LED_BUILTIN, HIGH);
}

void loop() {
  wdt_reset();
  if (INPUT_IS_CLEAR) LedOff();
  else LedOn();
}

Schematic: https://i.sstatic.net/0UNzF.jpg
(mistake on the schematic - I connected 5v to vcc and ground to ground)
If it matters, I'm powering the head unit and the arduino from the 12v and 5v rails of an ATX power supply. They both take the same ground.
My code should theoretically only turn on my led whenever the head unit broadcasts bits, but it's just sort of erratically blipping on and off or fading gently at random. I've triple checked my wiring (breadboard if that matters). Why is this happening? Is there something about bit_is_clear(ACSR,ACO) that I don't understand?

Oh dear, the Wayback Machine. Sympathetic to your problem as I am, your question already refers to a link-dead site which is why you are using the Wayback Machine. Who knows how long that will last? Please post (edit your question) to include the schematics you are talking about, and the code. As it is you are saying "some link-dead site has a schematic and some code, how does it work?". Even if we answer, how useful will the answer be if the Wayback Machine goes down?

Done. Didn't think about the wayback machine dying out.

No, you haven't included the schematic nor the code in the question. If you dump it to your disk, then edit the question and include it, then the question will stand whether or not the Wayback Machine goes down, or any other site (excepting this one, of course, but then the question won't exist either).

The code is large and separated into multiple files. I'm not trying to make this post impossibly large.

About your recent edit: 1. “leave the pins tri-stated” means they should be set as inputs. 2. The analog comparator compares the potentials of the pins AIN0 (digital 6 on the Uno, not A0) and AIN1 (digital 7). Frigon has these pins connected to the AVC bus, whereas on your schematic they are left floating, so they only pick up noise.

Changing the pins is all I needed. I misinterpreted the pinout. I'm capturing messages like a champ now. Thank you so much.

Does [bit_is_clear(ACSR, ACO)] have something to do with something
  called in Internal Analog Comparator?

Exactly. ACSR is the “Analog Comparator Control and Status Register”.
ACO, the “Analog Comparator Output” is one bit of this register. The
ATmega328P has the same comparator, with the same register and bit names
as the ATmega8. C.f. the datasheet. You should be able to use this
part of the code as is.

Frigon has wired his Atmega8 in a peculiar way. [...]

It seems to me that is termination is intended to ensure that, in the
“floating level”, the line AVC− is at a potential higher than AVC+. In
the “driving level”, the opposite should be true, with a difference of
at least 120 mV.

I attempted to create something similar using while(digitalRead(2)) ;

It's not surprising that it doesn't work. This is a differential bus.
The information is carried by the potential difference between AVC+ and
AVC−, not by the potential of a single wire. A difference higher than
120 mV should be interpreted and a high state. Your digital input
instead reads a single wire and compares its potential to ground. The
thresholds to switch between LOW and HIGH are typically around 2.1
and 2.6 V, with some hysteresis. This is far from being compatible
with the signaling of the bus.
I recommend you follow Frigon's steps and use the analog comparator just
as he does. The comparator will tell you which of AVC+ or AVC− has a
higher potential, and it will not be bothered by the low level of the
differential signaling.

Thank you. I'll revise my approach and give that a shot. I deviated from the original work because I didn't understand it (and I really hate doing something without understanding it). To that end, is there anywhere I can read about the ACSR and ACO registers (and the comparator) in greater detail? Besides the 328P datasheet of course... That's a little too dense for me to work with...

If you narrow down your view of the datasheet to the page that mentions that register it isn't too bad. However I do find the explanation there rather obscure: "Bit 5 – ACO: Analog Comparator Output - The output of the Analog Comparator is synchronized and then directly connected to ACO. The synchronization introduces a delay of 1 - 2 clock cycles."

Edited original post with a followup on my issue after taking Edgar's advice.

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


text:
Properly using separate tabs with Arduino IDE
I'm trying to split up a large project of mine into separate tabs in the Arduino IDE and I'm having more than a few troubles with it. My main trouble is finding a way to have routines in extra tabs access the Serial object; because it's really hard to debug things with Serial.println() otherwise. All I get, though, is "'Serial' was not declared in this scope".
There appears to be some kind of trick to this? I've noticed that "byte" or "bool" needs to be declared in .cpp tabs and .h tabs but not on the main one?
Is there some kind of easy way to set this up so that I don't need to constantly #include <stdbool.h> and typedef unsigned char byte;?
Current issue: Main file:
void setup() {
  Serial.begin(500000);
  PrintMessage();
}

void loop() {
}

driver.ino file:
byte PrintMessge () {
  Serial.println("printin");
}

and on compiling:
error: 'PrintMessage' was not declared in this scope

EDIT: Found a silly typo. Problem solved.

Did you try #include <Arduino.h> at the beginning? That should expose the Serial object. Otherwise you'll need to show us the code files in which the error occurs.

This question is more about C/C++ header basics rather than Arduino. Anyways, you should have the following file structure: Code in .cppfiles, Header in .h files. Main sketch either .ino or .cpp (for cpp remember that you must explicitly write out the function prototypes!)
So for your small example that would be:
main.ino:
#include "driver.h"
void setup() {
  Serial.begin(500000);
  PrintMessage();
}

void loop() {
}

driver.cpp
#include "driver.h"
byte PrintMessage () {
  Serial.println("printin");
  return 0; //previously had no return although returning 'byte'.
}

driver.h
 //Always use include guards
 #ifndef DRIVER_H
 #define DRIVER_H

 #include <Arduino.h>
 //All function prototypes from driver.cpp.
 byte PrintMessage();

 #endif /* DRIVER_H */

Also corrected a typo from PrintMessge to PrintMessage. This is the "professional" way to do it, seperate implementation and header files.

Tabs are actually quite simple:

If it's named <something>.ino it will get merged with the main tab. It's just like working in one big file and you don't need to do anything special.
If it's named <something>.cpp or <something>.c it's a completely separate translation unit and has to be manually "enroled" into the Arduino system by including the Arduino.h header.

So it's simplest to just name them as INO files not CPP files and you don't have to do anything special:

That's not working out for me for some reason. I'm getting the compilation error No such file or directory at the line #include "drtiver.ino"

Why are you trying to include an ino file???

Because if I don't then I get errors that make less sense. Main file:
void setup() {   Serial.begin(500000);   PrintMessage(); }
driver.ino file:
byte ReadMessge () {   Serial.println("printin"); } Error 'PrintMessage' not declared in this scope.

Um... yes? You'd expect that when you have one calling PrintMessage and the other providing ReadMessage...

Typo. They're both PrintMessage(). Will edit comment as soon as it lets me.

See the images I posted in my answer. That works. If it's not working for you then you have done something else wrong. You will have to post more details in your question.

Main question edited.

You can't spell Message...

I'll assume that was a typo too...

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


text:
Explanantion of Addressing
I'm new Arduino user and I'm trying out a SPI protocol to interface a SRAM, specifically, the 23LCV512.
I have found the instructables steps to interface a SRAM using the SPI bus on an Arduino UNO very helpful (http://www.instructables.com/id/Interface-an-SRAM-bus-to-your-arduino/), but there is one  point that i would like some explanation for:
In the mem_demo.ino and other various SPI.h code, I have seen variations of the following, however I do not understand why you would have to do this? I think here that we are communicating the right shifting of an input address 16 places along with 8 bits of '1'.
SPI.transfer((uint8_t)(address >> 16) & 0xff);
SPI.transfer((uint8_t)(address >> 8) & 0xff);
SPI.transfer((uint8_t)address);

Commenting these lines out for the write did not effect the writing to the SRAM, but reading caused it to return mostly 0's.
I really appreciate any help iIget, I do not have a lot of experience with memory addresses and electronics, thank you.

It is actually slightly confusing owing to the (actually redundant) & 0xff in there.
What is happening is first the address is right-shifted so as to place the byte of interest at that moment in the lowest 8-bits (address >> 16 for instance to get bits 16-23 moved to bits 0-7) and then the lowest 8 bits are masked off by ANDing them with 0b11111111 (0xFF). This removes any bits that are above the 8 bits we are interested in - however the fact that it's cast to uint8_t and also passed to a function that expects uint8_t makes that masking redundant. Any bits above the first 8 are discarded anyway.
So to take an example address of, say, 100,000 (which is 0x186A0 in hex) and run those three commands on it, we end up with:
SPI.transfer((uint8_t)(address >> 16) & 0xff);

0x186A0 >> 16 = 0x00001
0x00001 & 0xFF = 0x01

SPI.transfer((uint8_t)(address >> 8) & 0xff);

0x186A0 >> 8 = 0x00186
0x00186 & 0xFF = 0x86

SPI.transfer((uint8_t)address);

(uint8_t)0x186A0 = 0xA0

The end result as you can see is three SPI transfers each sending a single byte:
0x01, 0x86, 0xA0

And that corresponds to the protocol for that chip, which is basically:
<Command>, <Address H>, <Address M>, <Address L>, <Data>...

For instance:
0x02, 0x01, 0x86, 0xA0, 0x69

You send the "WRITE" command, send the three bytes of the address you want to write to, then follow that with the data to write. Or you send the READ command, send the three bytes of the address you want to read from, then the data is returned to you a byte at a time.

It's kinda weird, that he's using 3B address, as it's 64kB memory and 16bits should be enough. So: 1B read command, 2B adddress, 1B dummy (or more) to shift out data from the device.

@KIIV The 24-bit address is a standard protocol. It's the same as for flash chips, and they come in megabyte sizes. You can't arbitrarily choose your protocol, it is dictated by the chip, and all the chips use the same standard.

For Flash yes, but this is the SRAM and according to the datasheet, it uses only 2Byte Address for direct access and 1B Address for page read/write

You're right, that one does only use a 16-bit address. So the OP should read the datasheet and modify their code accordingly. Also they should never trust anything they read on Instructables since it's completely filled with complete ****.

@Majenko Thank you for your thorough explanation, i have a lot more insight into what is happening on the memory level. I have been looking at SPI and SpiRAM code on github and have seen that they do not include the & 0xFF because it is redundant.

@Majenko I guess the only thing I'm a little unsure of now is why we don't start reading at address 0, 1, 2, etc, and why we would have to shift the addresses to read every 8 or 16 times. Am i right in thinking that the reason we shift address is because we read and write memory in '8' bits and more at a time, not a bit at a time?

You shift addresses because the Arduino's SPI routines can only handle 8 bits at a time, so you have to split the address into 8 bit chunks and send those chunks. Then you can read (or write) as many bytes from that address as you like (size permitting)


text:
How to convert byte array to float
How can I convert a byte array to float?
Code:
void send_data() {
    CCPACKET data;
    data.length=2;

    float lon=26.533255;
    float lat=27.533463;

    data.data[0]=lon;
    data.data[1]=lat;

    if(cc1101.sendData(data)){
    Serial.println(data.data[0]);
    Serial.println(data.data[1]);

    Serial.println(" sent ok ");
    return true;
    }else{
    Serial.println("sent failed ");
    return false;
    }

 }

The problem is when I print those two variables it just prints lon 26.00 and lat 27.00 but not lon 26.533255 lat 27.533463 as I expected.
Here is the header file for CCPACKET I use:
#ifndef _CCPACKET_H
#define _CCPACKET_H

#include "Arduino.h"

/**
 * Buffer and data lengths
 */
#define CC1101_BUFFER_LEN        64
#define CC1101_DATA_LEN          CC1101_BUFFER_LEN - 3

/**
 * Class: CCPACKET
 *
 * Description:
 * CC1101 data packet class
 */
class CCPACKET
{
  public:
    /**
     * Data length
     */
    byte length;

    /**
     * Data buffer
     */
    byte data[CC1101_DATA_LEN];

    /**
     * CRC OK flag
     */
    boolean crc_ok;

    /**
     * Received Strength Signal Indication
     */
    byte rssi;

    /**
     * Link Quality Index
     */
    byte lqi;
};

#endif

I was trying to fix it by this part of code, but without success:
float lon=26.533543;

*((float *)data.data[0]) = lon;

Can someone help me to convert the byte array to float?

Do you know how many bytes a float uses?

Hmm unfortunately no.

Your first task is to discover the answer.

You can choose to treat the byte array as a float array by typecasting. Your attempt isn't far from a solution:
((float *)data.data)[0] = lon; // uses data.data[0] ... data.data[3]
((float *)data.data)[1] = lat; // uses data.data[4] ... data.data[7]

When printing you should also treat the data array as float array:
Serial.println(((float *)data.data)[0]);

It looks like you are sending the data over some interface. Then of course you need to typecast the binary data back into a  float at the receiving end (if you want to do something useful with it) - similar to what is done above when it is passed to Serial.println.

Hi thank you for helping me, it was useful :) Now it is possible  to send data with decimal. I was trying to receive data like this:                                                      loat lon=((float *)packet.data)[0];
float lat=((float *)packet.data)[1];
  Serial.println(((float *)packet.data)[0],4);
  Serial.println(((float *)packet.data)[1],4);              But without success. What could the problem be? Again I want to than you :)

The output I got is 0.0000 and 0.0000

Did you update the packet size (data.length)? Each float eats 4 bytes, so it has to be 8 now.

Hi, I'm not able to fix it by my self. How/where can I update the the packet size?

Try data.length=8 in your send_data routine.

Aha you are right :) Thank you for helping me :)

/**
  Data buffer/
  byte data[CC1101_DATA_LEN];

That line of code declares an array of datatype byte. I suggest you review variable declaration for Arduino.
A byte will store an 8-bit unsigned number with a range of 0 to 255, no decimal points. I also suggest you review truncation to understand how computer systems handle mathematic calculations that produce decimal results when the result is being stored in a variable type that doesn't store decimals.
A float stores a 32-bit value with decimal point.
The quick answer to your problem is to change the above quoted code from byte to float.

Except now the CC1101 code will need to be changed to accept floats and transmit bytes. So, nothing saved.

True, it would have to be followed through with on all related functions. It could get messy. In any case, the issue is that CC library is set up for bytes rather than floats.


text:
Arduino Mega & WiFi Shield; why web server every time says my A7 pin reads 0V?
I have got Arduino Mega 2560, Arduino WiFi Shield and resistor 1.5K.
Now PWM 2 is attached to the resistor then attached GND. 5V is attached between PWM2 and resistor's up point. I want to read the Arduino Mega's A7 analog input point in order to print this value on an Android Phone's web browser but, I get zero value every time surprisingly. It should be like 235, 350 something like integer or float kinds as usual.
According to Android Phone's Google Chrome Web Browser Page, why there are too many zeros in the HTML? It should be different from zeros because I have already added a short wire to Analog A7 so as to make an antenna.
A photo of my setup:

Screenshot of my Android web browser

Serial Monitor output

My code:
#include <SPI.h>
#include <WiFi.h>

char ssid[] = "Connectify-me";
char pass[] = "***";
int status = WL_IDLE_STATUS;
float PPG = analogRead(A7);
boolean door_status = false;
WiFiServer server(80);
void setup() {
  Serial.begin(9600);
  while ( status != WL_CONNECTED) {
    Serial.print("Yazdigin SSID araniyor: ");
    Serial.println(ssid);
    status = WiFi.begin(ssid, pass);
    delay(10000);
  }
  server.begin();
  printWifiStatus();
}
void loop() {
  WiFiClient client = server.available();
  if (client) {
    Serial.println("Deger gonderildi");
    Serial.print(PPG);
    while (client.connected() & client.available()) {
          client.println("");
          client.println("");
          client.println("
");
          client.print(PPG);  //The value should different from zeros but everytime 0
          client.println("
");
          client.println("
");
          client.println("");
          client.println("");
      }
    }
    delay(3000);
      client.stop();
      Serial.println("client disonnected");
  }
  void printWifiStatus() {
  Serial.print("Baglandigimiz SSID: ");
  Serial.println(WiFi.SSID());
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Addressi browserda ac: ");
  Serial.println(ip);
  long rssi = WiFi.RSSI();
}

Step 1 in troubleshooting is to create a minimal example. The Serial.print(PPG); shows 0, so all the web server stuff is irrelevant. You need to narrow your scope to isolate the problem.

Use images that add information to you question. A screendump of the code and a screendump from 0-values doesn't add to the information, it even distracts. A proper circuit diagram would normally be welcome, but after analyzing your writing and the picture I concluded that all this question  is about, is a dangling wire. Don't put up a smoke screen, as sachleen mentioned, it is very important to narrow down to what you actually want to know and that is not limited to minimal code to reproduce the issue. It took me several minutes (and considering to leave the question unanswered) to understand

You are reading the input pin float PPG = analogRead(A7); only in the startup code of your program. Move that into the loop to have it updated before using it.

Yes, I have already did this. Still, not a remedy for me.

The capacitor in the sample-and-hold circuit in the ADC frontend is tied to ground and it is very leaky. Unless you have a low or medium impedance output connected to it, you will always read the ground value. An antenna is a very high impedance device.


text:
Sending Analog Data with and IR LED
This is the idea. I have 2 Arduinos. One with an IR LED and the other with an IR receiver. I want to read the values of multiple sensors and transmit it to the other Arduino via IR. I know how to send data like a fixed HEX code but I dont know how to send values from a potentiometer.
Just think of how a quadcopter sends and receives data from the joysticks, thats somewhat what I want to do.
[EDIT]
This is a precision of what I want to do. I'll read the values of let's say 2 potentiometers, map the values from 0-99, and then I want to send it to the other Arduino with IR and not anything else.

The protocol used by toy IR helicopters has been thoroughly reverse engineered and documented, you should be able to find it with a web search.

Is your question: "How do I send a variable by IR as opposed to a constant?" Or is there more to it?

@NickGammon, yes.

Well, if you can manage with 8-bit data, just send a byte at a time. Otherwise you need some sort of protocol, like <123> and have the receiving end detect the delimiters. That's what the answer by axa said.

Seems to me you first need to establish a protocol.  Could just be a simple one you make up,  with it you will eventually find that repetition and retransmission will need to be explored, and you may want to include things such as a CRC if the application suits it; or not...
As part of the thought process you need to look at your sensors, see how they put out their data, you seem to indicate analog, so that would be read on an a to d converter and that d value might be directly sent as the data part of your chosen protocol.
Or some joysticks packages might have have a I2C or SPI driver built in to which the A to D wouldn't be required.
But using IR you will find timing and validation very important so that the receiver knows where the beginning and end of data is at.
Thinking about it there must some libraries out there already.
Or entirely completed projects to study.
Now you didn't ask but if reliable communication is desired you might want to go wired serial or use a managed protocol like an Ethernet peripheral.


text:
Why does an `.ino` file have to be in a folder of the same name?
I'm trying to organise a very complicated project and I want to put all the actual code in a folder named src (source), but I want to keep the main .ino file as main.ino (it will also be in src). Then when I try to open the code, the IDE says that main.ino has to be in a folder named main.
Why is this?
I fully understand the error message, but why does the file naming in Arduino has to be so. Is there a way to change that?

AFAIK, that is a quirk built into the Arduino IDE. The best workaround I can think of is a file structure something like:
ArduinoWorkspace --- /myproj/ ----+ /src/ --------+ myproj.cpp
                                  + myproj.ino    + sensor.h
                                                  + sensor.cpp
                                                  + (more files)

, where myproj.cpp just #include's main.cpp. This should leave your project files "clean" such that they should work in a more typical environment as well.
Update:
I borrowed the name "main" from your question, but on reflection, "main" is a reserved name, specifically, every C or C++ program has a main.c or main.cpp as its top level code, provided by the system if you don't provide one. So I avoided using that as the folder- and project-name (but feel free to try it) and I've updated the diagram. What you do need is a project folder and a .ino file within it, of the same name. The .ino file could
#include <src/anything-else-you-like>

, e.g., your top level code file, thus pulling everything else. You may need for your .ino to #include each of the files in the src folder, if it the compiler doesn't figure out on its own, that that's where your other files are.
BTW, if you do use the name main.cpp for your top file, it will have to call the setup() and loop() functions (and serial event function, if you use that). It's probably best to leave the name 'main' alone, let the system provide the same main every Arduino program gets by default, and write your project code the typical Arduino way -- starting with setup() and loop().

myproj.cpp, you mean myproj.ino? Because I don't see where myproj.cpp is!

Ok, little problem, if I do this, some basic Arduino functions (such as map() and analogRead()) that are contained in sensor.cpp won't be recognize by the compiler.

Alternatively, if working on a Windows box, use the junction command and "link" a correctly name directory to the directory with the better name.  Or, if working on a Linux box, use the symbolic link command to do the same.

(See my update - your .ino file might have to include each of the other files).

Could you please update your answer? You are mentioning files that are nowhere to be found in your folder structure.

If I understand correctly, when you open your proposed structure in Arduino IDE, you only see myproj.ino, and cannot see the content of any of the files in src? So you can only an almost empty ino file, and none of the actual code? Oh boy, Arduino IDE project structure is completely stupid.

You can also avoid the Arduino IDE project structure entirely by compiling C++ code like a normal microcontroller. https://arduino.stackexchange.com/a/90438/52996

When you have a project made up of a number of .INO files, how is the IDE supposed to know which is the "main" one? During compilation the IDE concatenates all the .INO files together into one monolithic file. It does this starting with the "main" one and then appends each of the others alphabetically to the end.
It is done this way so that your includes and global variables, which you should put in your "main" .INO file, are at the start of the finished program.
In order to do this the IDE has to know which of the files is the "main" one. And the way it works that out is by finding the one which is named the same as the folder the sketch is in.
In UECIDE I take it a step further and turn the whole folder into a compound document so you no longer have to enter a folder and open a .INO file to open a sketch - the actual folder itself is the whole sketch project. Again this kind of folder is identified as having a .INO file within it that is named the same as the folder.

in fact, for me the IDE wants to move the proj.ino file even when it is already in a directory proj/ (and it is the only .ino file in that directory but there are other files in the same directory), i.e. it wants to move it to proj/proj/proj.ino. At some point I'll reach the maximum path length of the file system...

it turns out that in my case I had a few softlinks pointing nowhere in the directory of the .ino file. Removing them seemed to solve the problem...

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


text:
Controlling voltage and current from chip?
I'm well aware that this question perfectly showcases my spectacular ignorance, but oh well. It's a simple enough question, so here we go.
I have a 595 chip (SN74HC595) wired up to an Arduino, fed by the 5V output. After switching all the outputs on, I measured an output pin at 5.04V and 74mA.
I want to use the chip's outputs to switch transistors (P2N2222A) which will have 60 mA through them (switching common cathode RGB LEDs), so I believe I need to drop it down to around .6 to 1.2V at .6mA, right (I'm not at all sure I'm reading the datasheet right)?
So how exactly do I do that? It seems like I need to put a resistor in between the pin and the base, but don't I need to know the TOTAL resistance of the circuit? Or can I just calculate from the pin itself (I believe that would need 7K)?
Thanks in advance for your help, and please feel free to OVER-explain if you're so inclined.
EDIT:
EDIT 2: Resistor values are listed wrong. R1=200, R2 & R3 = 100.

74mA was your total draw (including arduino?)    I am very confused what your trying to do here.  Please provide a schematic showing what you have/ what you intend on doing.  I am fairly certain your assumptions about the 1.2V/.6mA thing is wrong, but not sure exactly what your talking about yet

Added hurriedly thrown together schematic.

You dont need the transistors or the IC to turn on those two LED's. Right now, both LED's will be the same(is that what you want) but you can just connect them to ground(remove transistors and IC) and then control their colors via the pins(6,5,4).   Also no sure why you have different value resistors for each color, the 100, and 200 ohm ones are too low. I would suggest at least 680ohm, but the 1k should be fine too

Connecting an ammeter between a pin and ground is silly. That's just like shorting the pin to ground, and will show the maximum the chip is capable of, which is usually far more than it's rated for.

@ChadG, the transistors are there so that I can expand the circuit beyond two LEDs. I realize I could simply drive two LEDs directly from the board's PWM pins, but there are only 6 of those, limiting me to two LEDs. This way I can switch them on one at a time fast enough that they appear to remain lit.
I did mess up the resistor values, but they should be 200, 100, and 100. The red part of the LED drops 2V and needs 20mA, so (5-2)/.02=150, rounding up to the nearest resistor value I have. The blue and green drop 3.2V, so (5-3.2)/.02=90, rounding up to the nearest resistor I have.

@Majenko, thanks for the information. Like I said in the question, I am spectacularly ignorant about electronics.

There should not be that much of a voltage drop on an led

why do you think that shorting an output to ground is equivalent to no load?  .... try shorting a battery, and then tell me if you still think the same thing

@jsotola because I've only been learning this stuff for about a month now. I take it from your answer it's not. So is the load then the meter? The wire? Please explain more.

You're misunderstanding what you need to drive a transistor.
A transistor will allow up to a specific amount of current through the collector depending on the current that flows through the base. If less is needed by the load then less will flow.
Think of it like a tap. If there's not much water pressure it doesn't matter how far you turn on the tap, after a certain point the flow of water won't increase any more.
To allow 60mA through the collector you need to provide at least 0.6mA (assuming a hFE of 100) through the base. That 0.6mA will set the upper limit of the current to 60mA. If you provide more than 0.6mA then you will allow a higher upper limit.
The 0.6V on the base is the voltage (difference between base and emitter when wired as "common emitter") at which current will start flowing through the base. It's the same concept as the forward voltage of an LED. For switching the voltage you put on the base must be more than 0.6V to allow current to start flowing. Since 5V is more than 0.6V you don't need to worry about it.  If you want precision in your calculations you will want to take that 0.6V into account, though.
So if you want at least 0.6mA from 5V with a 0.6V drop on the BE junction, you need:
R=V/I = (5 - 0.6) / 0.0006 = 7.3kΩ.

That's the maximum resistance you want. Anything more than that and the current through the base will limit the current through the collector to below the 60mA you want.  So you must select some resistance that is lower than that.
What value? Well, it really doesn't matter that much. The lower the value the higher the current, but at these levels the current levels you're dealing with will be minuscule anyway.
It's common to use a 1kΩ resistor in the base for a transistor when using it as a simple switch like you are.  That would give you, for each transistor:
I=V/R = (5 - 0.6) / 1000 = 4.4mA

For all 8 outputs that's a paltry 35.2mA. Far below the total the chip can provide of 70mA.
If you care about current consumption (you're running from batteries, for instance) you may want to increase to 4.7kΩ resistors to reduce the total drive current down to 7.5mA.

Thank you for such an in-depth explanation. I'm trying to make sure I've wrapped my head around this. I'll try out some of your examples tomorrow. Will putting the ammeter across the resistor give me the correct current?

Ammeters go in series with the connection, not parallel.

So in terms of calculating the voltage and current, I treat the pin as a 5V DC source?

Well, that's what it it...

Thanks again for the great explanation. Tried it out with some 2K and 5K resistors (making sure to put the meter in SERIES for current measurements this time), checking against the math, and I see what you're saying. :D

You are making the design more complicated than it needs to be.
Use a WS2803 chip, it has 18 outputs, 0-255 PWM level programmable for each output.  Got more LEDs? Use more chips.
http://da-share.com/files/datasheets/WS2803.pdf
Or use WS2812B RGB LEDs, easy to wire up in a daisychain. SMD typically, and Sparkfun carries 2 thru hole variants also.

Thanks for the tip, but I'm aware that this isn't the optimal or easy way to do this. I've actually already ordered some PWM expansion chips (TLC5940), but they haven't arrived yet, and won't for about a month.
So I'm trying to figure out how to do it with what I have on hand, and what I have on hand is a dozen or so 595s. Besides, I'm learning more this way. :D

Where did you order from? Digikey.com or Mouser.com would have had them to you in under a week in the US.

Chinese crap off ebay. I know, "boo, hiss". And I know there's a good chance of them not being authentic or good quality, but I'm just tinkering around on my kitchen table here, so...
Also, I am not in the U.S.


text:
Arduino IDE can't program my Arduino Pro Micro
I have a lot of Arduino Pro Micros that I can't program through the Arduino IDE.
I'm on Windows.
I'm using the SparkFun Pro Micro board information downloaded from SparkFun's website.
I've tried manually reassigning the Pro Micro's COM port in the device manager. It seems to be no different whether I'm at COM1 or COM255.
If I use an Arduino ISP or USBASP to burn the bootloader onto the problematic Pro Micro, it responds for usually one or two more USB programmings but that's about it.
When they get into this problematic state, they are still running their code (I can see the Blink sketch flashing my LED for instance), they just can't be reprogrammed. I can even still open their Serial communications.
Verbose output during the uploading process on first attempt yields the following:
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
PORTS {COM1, COM2, } / {COM1, COM2, } => {}
Uploading using selected port: COM2
C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -PCOM2 -b57600 -D -Uflash:w:C:\Users\Thompson\AppData\Local\Temp\arduino_build_668056/BareMinimum.ino.hex:i

avrdude: Version 6.3-20171130
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM2
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         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 : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding

That last line is where it freezes for an indefinite period. I close and reopen the Arduino IDE and try to reupload, and this is my result:
processing.app.debug.RunnerException
        at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:160)
        at cc.arduino.UploaderUtils.upload(UploaderUtils.java:82)
        at processing.app.SketchController.upload(SketchController.java:736)
        at processing.app.SketchController.exportApplet(SketchController.java:703)
        at processing.app.Editor$DefaultExportHandler.run(Editor.java:2039)
        at java.lang.Thread.run(Thread.java:748)
    Caused by: processing.app.SerialException: Error touching serial port 'COM2'.
        at processing.app.Serial.touchForCDCReset(Serial.java:107)
        at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:144)
        ... 5 more
    Caused by: jssc.SerialPortException: Port name - COM2; Method name - openPort(); Exception type - Port not found.
        at jssc.SerialPort.openPort(SerialPort.java:167)
        at processing.app.Serial.touchForCDCReset(Serial.java:101)
        ... 6 more

This exact same message (with a different COM number of course) plays out on any Windows machine I try this with.
In the above example I was trying to upload the Bare Minimum example.
Are all of my Pro Micros dead? Is there something wrong with the IDE? Is there an alternative IDE I can get a second opinion from?
EDIT: An update; I've gotten Atom installed with PlatformIO and I was able to write a few sketches to an Arduino Pro Mini. I attempted the same sketches on the Arduino Pro Micro and got the same error and freeze: programmer is not responding

the Micro has a MCU with native USB port handled by the sketch (the part from Arduino core). if the sketch hangs, USB is not handled. then you must activate the bootloader by reset or double reset

That's really useful information. So do you mean that if I have a ten second delay in my main function, the serial port would only be handled once every ten seconds?

no. it runs with interrupt

After experimenting some more, it looks like this issue is related to a one second watchdog that I have enabled in my sketch. After removing the watchdog, I've had no problems (so far) with uploading code.

It is OK to accept your own answer as the solution to the problem.


text:
Why Commenting Serial.print() gives me a different value?
I am working on with Cypress and Arduino.I am trying to transfer the data from cypress and printing it to the Serial Monitor or Arduino. but the thing is when I am using Serial.print(j) it is showing the right value of i (See in the code about what is i and j), but when I comment or remove Serial.print(j) it is showing the wrong value of i
For example, suppose cypress is sending data 00001934a
and then I am reading this value using
int j = mySerial.read()-'0';
// -'0' is for chaging ascii data to normal integer
//for example ascii value of `0` is 48
//so mySerial will read 48
// and exprerssion value will become `48-48 = 0`

My code
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX
void setup() {
Serial.begin(57600);
 while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

mySerial.begin(4800);
}

int  i = 0;
int j = 0;
void loop() {
if (mySerial.available()) {

        while(j!=49){
        i = i*10 + j;
        j = mySerial.read()-'0';
         //49 is the ascii value of a, I am using this for acting like
         //a flag, so that i can see the break in data

        Serial.println(j);//commeting this line is causing the problem
      }
   Serial.print(i);
   }
}

when the line is not commented the output was
0
0
0
0
1
9
3
4
49
193 //this is the value of i which is correct one

but when I comment the line Serial.println(j) the output was
   14569 // I don't know what the hack is this.

Hopefully the problem is understandable, but still, you can comment for more detail.
BTW I am using SoftwareSerial.

Try now, I have only shown the problem, not all code, but still, it is compilable.

Majenko has correctly diagnosed your problem, and the blog post he
linked to is definitely a must-read. The suggested solution, namely
buffering the input until you can read a complete message, is presumably
the most standard way of dealing with an input stream.
It is, however, not the only option. Your idea of building the number
digit by digit can work, if implemented properly, and it can save you
the memory cost of the buffer. The key is to only read bytes when they
are available.
Below is a non-blocking implementation of a number reader that works
along the lines of your own code. This function only reads positive
numbers. It returns the number it just parsed upon reading a non-digit
character. In every other case it returns -1 to tell you there is no
input number available:
// Read an positive integer from a stream.
// Returns -1 if a complete integer is not available.
int readInt(Stream &link)
{
    static bool got_a_digit = false;  // did we get a digit so far?
    static int i = 0;                 // the integer we are building
    if (link.available()) {
        char c = link.read();
        if (isdigit(c)) {
            i = 10 * i + (c - '0');
            got_a_digit = true;
        } else if (got_a_digit) {  // non-digit: return the number
            int i_copy = i;
            got_a_digit = false;   // reset for next reading
            i = 0;                 // ditto
            return i_copy;
        }
    }
    return -1;
}

And here is how you would use it:
void loop() {
    int i = readInt(mySerial);
    if (i != -1)
        Serial.println(i);
}

Your serial reading is completely flawed:
if (mySerial.available()) {

    while(j!=49){
    i = i*10 + j;
    j = mySerial.read()-'0';

What you are saying there is:

If there is at least one character available:
Read as many characters as can until I get 49.

The main thing wrong with that is that you try and read characters that just don't exist. Serial comes in a byte a time and you must wait for those characters to arrive before attempting to read them.  By adding the serial print into your loop you are slowing it down and, by chance, giving the characters time to arrive.

Read this to better understand how serial works.

Please, Wait for some time, I'll post the real code.

That's a shame. However, if he's (as he probably is) doing the same thing in the "real" sketch (his post belies a fundamental lack of understanding of serial reading) then this is still likely the problem.

Sir, I know how the read(), function is working, it is reading one char like 0 and printing its ascii value to the serial montior. thats why I am using a flag, so that i an see the break in my data.

Except if that char hasn't arrived - it returns -1 instead (255 when mapped to an unsigned 8 bit value).

I have used if(mySerial.available()>0){Serial.print("something"); }to check wheather the data is coming or not

Yes - if there is one character available then try and read 8. That is wrong. Very very wrong. Read the blog post I linked to.

I should make it more understandable.I think.

@LookAlterno: According to my test, it does produce the value posted.

Oh look. All those -49s. Looks like -1 - '0' to me...


text:
Is it common that Uno clones misbehave when connected to 12v on VIN?
Edit: this was completely my mistake. See end.
My official Uno worked fine when powered by 12v on VIN, but my Uno clone acted really funny--it read random noise from an input when a simple wire was attached, but not with no wire. It was solved with a pulldown resistor. The worse problem was that the PWM didn't turn off when I called analogWrite(pin, 0). More worrying, it seemed to be outputting by power rather than duty cycle, since my small LED strip seemed to be doing higher duty than my big LED strip (both powered by transistors), though both were being set with analogWrite(pin, 0). I measured the 5v pin at 5.9v. The input voltage may have actually been up to 12.5 v, but clean. I disconnected VIN and hooked back up to USB, and everything worked fine.
I assume the solution is to either use a linear regulator wired to VIN, or a battery?

I did get the linear regulator, which didn't help. I finally checked all my voltages, and found there was a 0.8 volt difference between different grounds!  It turned out my breadboard was wired to the Arduino pin next to ground, instead of ground itself. I feel very lucky not to have ruined the board, and my only complaint is that the pins aren't labeled clearly as they are on my official Arduino. On the other hand, I wouldn't have been able to debug this as easily on the official Arduino, since the clone has lovely solder holes at each pin which are a great spot to stick a voltmeter probe.

you connected the uno clone to 12V without reading the specs for the board?

It may be naive of me, but I wasn't aware cheap clones had specs, at least specs that are in English. I thought they were supposed to work like the official ones, but with less reliable construction and components. Various internet sites indicate that clones max out at 12v while Arduino will handle 20v in a pinch, but I didn't think 12.3v (probably) would be over some hard limit.

the solution is to either use a linear regulator wired to VIN, or a battery - or stop using cheap chinese knock offs - I mean, clones :p

@JaromandaX You highlighted "cheap". Do you mean it's possible to find high quality knockoffs?

Clones. Yes off course

@JaromandaX I'd better ask a separate question about that. Are clones highly frowned upon in this forum? I live an hour from China, so I don't consider this to be an ethical issue like it might be for someone in the US or Italy. I mean, Arduino isn't marketed or priced for my demographic.

I'm not saying all chinese clones are poor quality either

I don't think there are any issues with discussing clones. This isn't the official Arduino website, and even there they have quite a lot of questions about clones, or indeed "home-made" boards which technically are nothing to do with Arduino, except that they might have an Atmega328P processor on them.

Have you tried to use INPUT_PULLUP mode on input pins? The CMOS circuits are basically high input impedance amplifiers and it catches all kinds of EMI.

@KIIV Thank you, is INPUT_PULLUP considered a best practice for using switches? That would save me a component. But it seems unlikely I would want a pulldown resistor on the base of an NPN transistor, right? The bad PWM output (going into the transistor bases) makes me think the board is going haywire, one step away from giving up the ghost.

For switches it's sufficient (maybe in environment with high interferences you'll have to use lower impedance). For driving NPN Base the OUTPUT mode is used and you have to use current limiting resistor (usualy about 1k).

i frown on using name-brand boards, but that's me; i like my money in my pocket.

Is it common that Uno clones misbehave when connected to 12v on VIN

Whether it is "common" is probably unanswerable unless you do some sort of survey.
However bear in mind that clones or "knock off" boards (some of which pretend to be official ones) are built to a price. The original Arduino was already designed to be cheap. To make them even cheaper the manufacturers may well make a number of compromises. For example, some use a cheaper USB interface chip. It wouldn't surprise me if the components like the voltage regulator, capacitors, etc. are under-specified.
I see from eBay that clones are already quite cheap, possibly around $US 4.50. To compete with that, some manufacturers may be cutting back even further on the quality of components.

I assume the solution is to either use a linear regulator wired to VIN, or a battery?

You are probably better off bypassing the on-board regulator entirely. Get a wall-wart that outputs 5V regulated. The sort of thing that might power a USB-based device. Then plug that into the 5V pin of the Uno (not VIN). In fact, virtually any mobile phone charger wall-wart will output exactly what you want. Just run a USB cable from that to the USB port on the Arduino, and there you have it! Regulated 5V power.

The other thing that could work would be to give the voltage regulator a break. Don't put 12V into it, put in 9V. Then it doesn't have to work so hard (that is, dissipate the extra voltage as heat).

I'm just outside of China, so these clones were $2.70. They weren't even the cheapest I could have bought.
A wall wart is the worst and last option--this project has a fixed location, and it would mean running an additional long power cord to it. However, I should be able to get a linear regulator to output 5V from the (required) 12V that's being supplied.
I'm also thinking about making a voltage divider--the fluctuation shouldn't be that bad if I let 500 mA flow through the divider with no load. But please let me know if this is a bad idea.

To clarify, if I use a voltage divider, I would be supplying 9 V to VIN (letting the Arduino take care of fluctuation), but if I use a linear regulator, I'll apply 5 V to the 5V jack (assuming there is no fluctuation).

@piojo: The issue with the divider is that the voltage you get is highly dependent on the current you draw. Depending on what the Arduino is doing, the current draw can vary quite a bit.

Check out my post about a temperature sensor that runs from batteries. There are much better ways than trying to put 12V into VIN.

@NickGammon That mosfet technique is really interesting! As for my original post, I edited it to explain that the board wasn't the problem. I wired ground to a floating pin (next to GND) instead of GND. So the problem is between keyboard and chair, unless you blame the board manufacturer for labeling that's not as good as the labels on an official Arduino.

Some of the labelling on alternate boards is almost impossible to read (for me). I thought that was just my eyes. :)


text:
Is DateTime from RTClib giving garbage dates/times?
The RTC is working fine, but I'm having trouble with the DateTime class. Based on the following test, it seems like its math is wrong.
#include <RTRlib.h>
void loop()
{
    auto ts = TimeSpan(0, 8, 0, 0); // 8 hours
    auto zero = DateTime(0, 0, 0, 0, 0, 0);
    auto alarm = zero + ts;
    Serial.println(String("Zero date: ")+zero.year()+" "+zero.month()+" "+zero.day()+" "+ zero.hour()+":"+zero.minute()+" "+zero.second());
    Serial.println(String("Alarm as timespan: ")+ts.days()+"d "+ ts.hours()+":"+ts.minutes()+" "+ts.seconds());
    Serial.println(String("Alarm date: ")+alarm.year()+" "+alarm.month()+" "+alarm.day()+" "+ alarm.hour()+":"+alarm.minute()+" "+alarm.second());
}

My output is (repeating):
Zero date: 2000 0 0 0:0 0
Alarm as timespan: 0d 8:0 0
Alarm date: 2043 4 30 1:31 44

Also, when creating DateTime(0), I would expect the hours, minutes, and seconds to be zero. That's not the case. What's up with this library, and how did it get to be so popular if it doesn't work?

What is the value of alarmTime?

DateTime(0) isn't really supported as the library only works on dates after 2000. DateTime(0) will set the date to 1970, which looking at the source code doesn't work. But almost nobody would care. As for your primary issue, I wouldn't know why it isn't doing what you expect.

Try using the year 2001, just to be sure.

@Gerben My mistake, alarmTime is removed. Thanks for spotting that.And I find it strange that DateTime(0) isn't supported, since that is the default constructor!

Any DateTime class will have some limits on the range of dates supported. Unless the practical limits are less that the documented ones, that's not a bug. However, you are right in pointing out that the default constructor is not useful. I just opened an issue on this point.

You are experiencing the consequences of code that doesn't do sanity checking. The library allows for dates that do not make sense (in addition to giving us all a new reverse-Y2K bug of assuming only dates later than year 2000.
When you create DateTime(0, 0, 0, 0, 0, 0);, you are saying to use Month 0 and Day 0. Those have no meaning in date calculations, which always assume that the first month is 1 and the first day is 1.
The rest of the library's code assumes valid dates, so when you give it invalid dates, unexpected behavior is to be expected!
Of you only modify your zero assignment to DateTime(0, 1, 1, 0, 0, 0); you will see behavior that is more expected.

Thank you, I suspected I was doing something stupid. But that doesn't explain why the other constructor returns dates when given a number of seconds (DateTime(0)). Whether it's seconds since 1970 or 2000 (it should be the former), it does not look like a usage error to use that API for any non-negative argument, yet it does not give a sane date for small numbers.

Note that an RTC is meant to track real time, and since year 2000 will never happen again, there is no “reverse-Y2K bug” in that library. Or rather, that's a closed (invalid) bug. It does have a Y2100 bug though, but that's a limitation of the RTC hardware.

@EdgarBonet The comment above the class definition is, "Simple general-purpose date/time class". It's also not private and not part of a namespace. So no, it's not a real time date class. It's a general purpose date class, which happens to be buggy. Irrespective of the fact that adafruit doesn't want to fix it in their fork.


text:
Controlling LED from web server
I have a LED attached to my Arduino wifi shield that I want to control from my PHP web server.  In terms of communication, should I

Make my Arduino a web server and then communicate with PHP web server via HTTP
Make my Arduino a web client and receive commands from my PHP web service.  I would parse the JSON response

Also my other question is should I communicate with JSON between my PHP web server or is there a better way to send commands to my LED light?

There's no need for either PHP or JSON. Simply detect when one of two URLs (say, /led/on and /led/off) has been accessed on the Arduino's web server, change the LED state, and return a 204 response.

Is it possible to do this when the arduino is web client instead of a server?

No. If configured as a client then you'll need to have some sort of way to communicate to the client the desired state, requiring parsing on the part of the Arduino. Fortunately you don't need anything particularly complex; a simple 0 or 1 in the response is likely to be enough.

i see. One more question. Say I am sending temperature data from a sensor on my arduino board to php server constantly.  If the temperature is over 25 degrees then my server would turn on the LED attached to my arduino.  How would that work? In this case would the arduino as a web client make sense?

I wouldn't have the PHP server handle this. Have a threshold on the Arduino and have the PHP server communicate with it to set it.

The REST protocol is ideal for this and there's a nice Sketch already written, called RESTduino on Github:
https://github.com/jjg/RESTduino
Basically (and loosely) REST treats a URL as a command.  Quoting from the RESTduino doc's:
"To turn on the LED attached to pin #9 (currently case sensitive!):
http://192.168.1.177/9/HIGH

This will set the pin to the HIGH state and the LED should light. Next try this:
 http://192.168.1.177/100

This will use PWM to illuminate the LED at around 50% brightness (valid PWM values are 0-255)."


text:
Setting ESP8266-01 up with AT commands
I am facing for the first time with the ESP8266-01 module, so sorry if will write any stupid things.
I bought this module and I wanted to check its parameters through AT commands. Following some guide and wiring schemas found on the web I finally hook the ESP8266 up with an Arduino Uno (as in the picture below. The resistors are 220ohm each and the capacitor is 100uF) in order to print out to the serial monitor the AT commands and responses.
I uploaded the following code to Arduino Uno:
#include <SoftwareSerial.h>
SoftwareSerial esp8266(6, 7);

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Started");

  // set the data rate for the SoftwareSerial port
  esp8266.begin(57600);
  esp8266.write("AT\r\n");
}

void loop() {
  if (esp8266.available()) {
    Serial.write(esp8266.read());
  }

  if (Serial.available()) {
    esp8266.write(Serial.read());
  }
}

But when I open the serial monitor (with both NL and CR selected and baud rate set to 9600) I got no response!!
If I try to send simple AT or AT+GMR commands, it returns to me nothing or random characters.
Does anyone please could tell me what I am doing wrong?

Try different common esp8266 baud rates. Different versions use different baud rates.

Also I know for a fact I have answered this very same question twice this month already.

This question is over a year old - have you solved your issue yet?

@Filipppo, please don’t just edit your title to say “solved”. That’s not helpful to anyone. If you solved it, please post the solution as an answer.

For future readers of this question, see my answer to a similar question, about Software Serial, ESP8266 modules and baud rate.

We faced similar problems when using ESP8266 for the first time, Following approach to the problem was fruitful

ESP8266 is 3.3v compatible so to avoid problems make a simple adaptor circuit to make it compatible with 5v Arduino (find details here)
First thing you need to do is check and confirm if you are able to communicate with your ESP module, you can use any USB to TTL interface and connect ESP Module directly with your computer/laptop. (explained in detail here)
Use ESP8266 configuration utility, it will speed up the ESP Module setup and help get the desired product develop faster. (explained in detail here)

Hope it helps.


text:
Synching local clock usign NTP to milliseconds
I am interested in getting a local clock on an ESP32 module synch to
a network clock using NTP. I am able to read data and time here. But I am interested in synching to the milli second level.
    #include <WiFi.h>
    #include <WiFiUdp.h>

    char ssid[] = "*************"; //  your network SSID (name)
    char pass[] = "********"; // your network password

    unsigned int localPort = 2390; // local port to listen for UDP packets

    IPAddress timeServerIP; // time.nist.gov NTP server address
    const char* ntpServerName = "time.nist.gov";

    const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes
    byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing
    // A UDP instance to let us send and receive packets over UDP
    WiFiUDP udp;

    void setup() {
      Serial.begin(115200);
      Serial.println();
      Serial.println();
      // We start by connecting to a WiFi network
      Serial.print("Connecting to ");
      Serial.println(ssid);
      WiFi.begin(ssid, pass);
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
      Serial.println("Starting UDP");
      udp.begin(localPort);
      Serial.print("Local port: ");
    }

    void loop() {
      //get a random server from the pool
      WiFi.hostByName(ntpServerName, timeServerIP);
      sendNTPpacket(timeServerIP);
      // send an NTP packet to a time server
      // wait to see if a reply is available
      delay(1000);
      int cb = udp.parsePacket();
      if (!cb) {
        Serial.println("no packet yet");
      } else {
        Serial.print("packet received, length=");
        Serial.println(cb);
        // We've received a packet, read the data from it
        udp.read(packetBuffer, NTP_PACKET_SIZE);
        // read the packet into the buf
        unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
        unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
        // combine the four bytes (two words) into a long integer
        // this is NTP time (seconds since Jan 1 1900):
        unsigned long secsSince1900 = highWord << 16 | lowWord;
        Serial.print("Seconds since Jan 1 1900 = " );
        Serial.println(secsSince1900);
        unsigned long mshighWord = word(packetBuffer[44], packetBuffer[45]);
        unsigned long mslowWord = word(packetBuffer[46], packetBuffer[47]);
        unsigned long mssecs = mshighWord << 16 | mslowWord;
        Serial.print("Frac Seconds = " );
        Serial.println(mssecs);
        // now convert NTP time into everyday time:
        Serial.print("Unix time = ");
        // Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
        const unsigned long seventyYears = 2208988800UL;
        // subtract seventy years:
        unsigned long epoch = secsSince1900 - seventyYears;
        // print Unix time:
        Serial.println(epoch);
        // print the hour, minute and second:
        Serial.print("The UTC time is "); // UTC is the time at GMT
        Serial.print((epoch  % 86400L) / 3600);
        // print the hour (86400 equals secs per day)
        Serial.print(':');
        if (((epoch % 3600) / 60) < 10) {
          // In the first 10 minutes of each hour, we'll want a leading '0'
          Serial.print('0');
        }
        Serial.print((epoch  % 3600) / 60); // print the minute
        Serial.print(':');
        if ((epoch % 60) < 10) {
          // In the first 10 seconds of each minute, we'll want a leading '0'
          Serial.print('0');
        }
        Serial.println(epoch % 60); // print the second
      }
      // wait ten seconds before asking for the time again
      delay(10000);
    }

    // send an NTP request to the time server at the given address
    unsigned long sendNTPpacket(IPAddress& address) {
      Serial.println("sending NTP packet...");
      // set all bytes in the buffer to 0
      memset(packetBuffer, 0, NTP_PACKET_SIZE);
      // Initialize values needed to form NTP request
      // (see URL above for details on the packets)
      packetBuffer[0] = 0b11100011; // LI, Version, Mode
      packetBuffer[1] = 0; // Stratum, or type of clock
      packetBuffer[2] = 6; // Polling Interval
      packetBuffer[3] = 0xEC; // Peer Clock Precision
      // 8 bytes of zero for Root Delay & Root Dispersion
      packetBuffer[12]  = 49;
      packetBuffer[13]  = 0x4E;
      packetBuffer[14]  = 49;
      packetBuffer[15]  = 52;
      // all NTP fields have been given values, now
      // you can send a packet requesting a timestamp:
      udp.beginPacket(address, 123); //NTP requests are to port 123
      udp.write(packetBuffer, NTP_PACKET_SIZE);
      udp.endPacket();

its not clear exactly how the fractional part of the seconds field is read from the NTP UDP packet. Here I have the code that reads the 4 bytes after seconds
unsigned long mshighWord = word(packetBuffer[44], packetBuffer[45]);
unsigned long mslowWord = word(packetBuffer[46], packetBuffer[47]);
unsigned long mssecs = mshighWord << 16 | mslowWord;
Serial.print("Frac Seconds = " );
Serial.println(mssecs);

Coding is hard enough, and its even harder if you put just like a sentence. If you have additional information, you can edit your question and put it there so that its easier to read and easier to notice.

hi dhimaspw..understood..newbie here. Wasnt sure how to add code to the comment box

The NTP timestamp format doesn't use milliseconds. All timestamps are in
seconds, in a 32.32 fixed point format. This means that the
fraction field is in units of 2−32 s, or about
233 picoseconds. You can convert that to milliseconds by
multiplying by 1000 and dividing by 232. For example:
uint32_t frac  = (uint32_t) packetBuffer[44] << 24
               | (uint32_t) packetBuffer[45] << 16
               | (uint32_t) packetBuffer[46] <<  8
               | (uint32_t) packetBuffer[47] <<  0;
uint16_t mssec = ((uint64_t) frac * 1000) >> 32;

If you want to avoid 64-bit arithmetic, you can instead divide by 128,
then multiply by 125, then divide by 222:
uint16_t mssec = ((frac >> 7) * 125) >> 22;

That should give the same result except for a potentially larger
rounding error. Note that, if you care about rounding, you would try to
round to nearest rather than towards zero:
uint16_t mssec = ((frac >> 7) * 125 + (1UL << 21)) >> 22;


text:
Switching external power supply to 5V cooling fan with an Arduino and 2N2222 transistor
I'm using a 2N2222 transistor as a low-side switch to turn a 5V computer fan on and off with an Arduino digital pin, which responds programmatically to a button press - i.e. the relevant digital pin is switched from LOW to HIGH for a determined time in response to a button press recorded on A0.
My circuit looks like this:

And here's my code:
#define btnPin A0
#define signalPin 6

void setup() {
  pinMode(btnPin, INPUT_PULLUP);
  pinMode(signalPin, OUTPUT);
  digitalWrite(signalPin, LOW);
}

void loop() {
  if(digitalRead(btnPin) == LOW){
  digitalWrite(signalPin, HIGH);
  delay(5000);
  digitalWrite(signalPin, LOW);
  }
}

For simplicity, I'm showing a separate button component in the diagram, but I'm actually using a button that's wired into an LCD shield.
My expectation is that, when I press the button, the digital pin wired to the transistor's base will cause the transistor to close the circuit and turn the fan (and LED) on for five seconds.
The problem that I have is that the Arduino's digital pin doesn't seem to be able to saturate the base, so not enough current passes through the transistor to power the fan. It does turn the LED on and off as expected, but the fan needs much more current than the LED. If I take a wire directly from VIN or the 5V pin and touch it to base (through a resistor, of course), it does succeed in saturating the base, and the fan turns on. Measuring the current from VIN (or the 5V pin) to base, I get 4mA, so my assumption is that 4mA is sufficient to saturate the base. My understanding is that an Arduino digital pin should easily supply this. But in my case, the current from the relevant digital pin to the transistor's base never goes higher than 1.4mA. I've tried different pins on the board, but always get the same result.
So the question is, why does the circuit work as expected for the LED, but not for the fan? Any help/suggestions will be greatly appreciated!

The transistor in the Fritzing pictorial is connected backwards (E and C swapped) . Please supply a schematic.

I did something similar with a S8050MD, which is similar to the 2N2222 but with higher gain. I also concur with @CrossRoads in his diode recommendation.

To fully turn the transistor on you should give the base somewhere around 1/10 to 1/20 of the collector current. If you read the datasheet for the PN2222 (a highly recommended activity) you will see that Vce(sat) is specified with Ic/Ib = 10.
Now, the Microchip ATMega328 MCU chip in many (but not all) Arduinos is capable of sourcing 10mA or 15mA with minimal drop (assuming a 5V supply), again this information is available in the MCU datasheet (Figure 31-71 on page 355).
So it appears you are using an "Arduino" with some other MCU. In which case you can either use another transistor to boost the current or substitute a logic-level MOSFET.

What manner of Arduino are they?

Then it should work. My assumption now is that you have E and C swapped on the transistor.

@artocignus It will work with E&C reversed, but will have very low gain. Or the transistor is damaged (eg. from overheating).

That's correct. You actually have the old metal can type, eh? Rare.

Based on the description of your circuit, it sounds like you might not have connected the Arduino's ground to the "negative rail", the same part of the circuit where the transistor's emitter is connected. You must make that connection in order to properly bias the base-emitter junction of the transistor.
I recommend you draw a schematic for this sort of question, that would be helpful.

I seem to have solved the problem. As mentioned in the question, I was using a button wired into an LCD shield. As the LCD shield occupies all the header pins on the Arduino, the LCD shield helpfully provides circuit connections for the unused Arduino pins. It seems that the LCD shield I was using has some fault which only allowed limited current to flow from the corresponding Arduino pins. This would explain the anomaly that only the LED lit up as expected, but the fan failed to work: presumably the weak current into the transistor's Base created sufficient gain to power the LED, but not the fan. Eventually, after many attempts at getting the circuit to work, even the LED stopped working and that's when I realised that there must be a continuity problem with the header connections. So, removing the LCD shield and wiring everything directly into the Arduino with a separate push button, everything started working as expected. Many thanks for all the helpful replies. I've got a much better handle on how BJTs work now!

You should also have a diode across the motor, cathode to 5V and anode to the transistor.
When the transistor turns off, the motor will try and keep the 200mA current flowing. The diode lets that current dissipate. Without it, you can get a high voltage spike at the transistor which can damage it.

Thank you! This is actually one of the questions I had. I did put a flyback diode in the final circuit, just in case. Good to know that it isn't superfluous!


text:
Getting "avrdude:stk500_recv(): programmer is not responding" while uploading sketch to Arduino Pro Mini
I recently bought an Arduino Pro Mini(3.3V 328p, 8MHz) along with a CP2102 USB to TTL UART convertor. When I try to upload a sketch to the Pro Mini using it, I get a avrdude:stk500_recv(): programmer is not responding error. My connection was like
Arduino pro mini                CP2102
TXO  ----------------------------> TXD
RXI  ----------------------------> RXD
VCC  ----------------------------> 3V3
GND  ----------------------------> GND
DTR  ----------------------------> DTR

I tried inter-connecting the TXO and RXI pins and had no luck. Also pressing and releasing the reset button on the Pro Mini doesn't seem to work either.  I also tried programming it with my Arduino Uno, by removing the 328 and connecting correspondingly. Still no use.
Does any one have any ideas?

Are you using avrdude at a command line?  If so, what command?  Or are you using arduino ide?  If so, what are the settings under Tools, Board and under Tools, Programmer?  (Please edit the answers to these questions into your question, instead of answering in comments)

@jwpat7 No no using Arduino IDE 1.0.6 for Mac. Actually the error is avrdude:stk500_recv(): programmer is not responding

Which port did you select?  Did you install a CP210x driver on your Mac?

Ok, so you are using the Arduino IDE. What are the settings under Tools, Board and under Tools, Programmer?

@ChrisStratton Yes i did install them

@jwpat7 I choose the correct port and set Board type as Arduino Pro or Pro Mini (3.3V, 8 MHz) w/ ATmega328.

First of all the Tx and Rx lines should be cross connected (Rx <> Tx). Images of the two boards would help I think, are you sure your CP2102 board has a DTS output and not RST(which can't be used as DTR)?

@alexan_s I tried cross connecting the Rx and Tx. It didn't work out.

Are you sure the board has a bootloader?

Double Check Your Code Errors and hold reset button until start uploading , I got same error at programming Arduino Mini Pro.

rx -> tx
tx -> rx
Please check your connections.

I had the same problem and I used a magnifying glass to check the processor.  I bought my clones off of eBay and they are using the ATMega168 (3.3V, 8 MHZ) processor.  Once I realized my mistake and switched to the correct processor version, the upload was seamless.
I'm using an "FTDI FT232RL USB to TTL Serial Converter Adapter Module 5V and 3.3V For Arduino" for the programming connection, with

DTS-DTS;
Rx-Tx;
Tx-Rx;
VCC-VCC;
GND-GND, and;
GND-CTS.

I didn't even need to use the "reset" workaround of holding down the reset button before pressing the upload button and releasing when the words "Maximum is ..." appear in the output window.

Change baudrate to
UPLOAD_RATE=57600

in Makefile (or via the GUI). I have seen your error many times and this fixes it, albeit on the 5V/16MHz mini USB variant. If 57600 does not work, try other values. I use this rate on my USB serial - may be different on bare Rx/Tx pins.
You have probably not messed up your bootloader, that is rarer than people think. I think your Arduino has some invalid code running, and it keeps resetting until it finds valid code - when I had that problem, I pressed reset just before punching enter for 'make upload'. Even if it does that, you've got perhaps 0.5s to initiate an upload after reset.
Do correct me if I'm wrong.

As above, it was the upload rate of 57600 that saved the day for me - thanks

Check connections, make sure RX-TX lines are crossing over.
Arduino -> Preferences -> Show verbose output during - check upload will give you better visibility what is happening.
When Arduino says "Uploading..." briefly press reset. The upload should start.

But one thing that helped me was... try different USB-UART adapter. For some reason the one which looked like (and was) cheap knockoff worked like a charm.
As a general advice, when sourcing parts from Chinese manufacturers I learned to be redundant - I usually order a bit more than I need and from mixed sources.

In the Arduino IDE for my Pro Mini I have to select the board:
"Arduino Deumilanove or Diecimila"
I'm not sure why this is or if this could cause any potential damage to your Pro Mini but I do know for sure this is the solution I used to program my pro mini and it works every time.

If this is a cheap clone it may be that there is no bootloader installed. You might try using a programmer or an Arduino as ISP to reprogram the device if this is the case. Using ISP programming will avoid any problem with serial connections as it is using SPI wiring instead and the Arduino IDE allows you to load the necessary bootloader using this method to enable programming over serial. You will need either an ISP programmer or another Arduino however.

no no bootloader was installed. In fact the it came with blink sketch preloaded. I tried reinstalling bootloader and had no luck. Any way now seller had agreed to replace the item.

You should try another USB port, install the right drivers for the TTL/uart chip and reboot your PC. That worked for me.

Also, you should consider getting an arduino nano usb, these have an built in ttl/uart converter, ICSP header and can be placed on a breadboard easily.

Well I am using Ubuntu and I can see the UART convertor getting recognized correctly. The nano is too big for my project. I am right now checking up ATTiny 85 from digispark

Can you also see the converter in your Arduino-editor?
and are you sure you have selected the right mcu?

Yeh in fact the transmitter pin on the UART blinks when I begin flashing of programs

Hoe about pressing the reset button just before it uploads, worked for me once

I tried that out. Didn't worked

The problem is crystal clear in the picture

This has absolutely nothing to do with the question asked.  It's not even the same board(!)