Simple GET request with ESP8266HTTPClient I am trying to do a simple GET request. But I always get status code -1. Here is my complete code.

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

WiFiClient client;
#define AP_SSID "CCR"
#define AP_PASSWORD  "ccrxxxxx"

void wifiConnect() {
  Serial.print("Connecting to AP");
  WiFi.begin(AP_SSID, AP_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
}

void setup() {
  Serial.begin(9600);
  pinMode(0,1);
  Serial.begin(9600);
  delay(300);
  Serial.println("starting");
  WiFi.disconnect();
  Serial.println("disconnected");
  wifiConnect();
  Serial.println("Connected");
}

void loop() {
  HTTPClient http;
  http.begin("https://calm-falls-41696.herokuapp.com/api/v1/cards");
  http.addHeader("Content-Type", "application/json");
  int httpCode = http.GET();
  Serial.println(httpCode);
  if(httpCode == HTTP_CODE_OK) {
  Serial.print("HTTP response code ");
    Serial.println(httpCode);
    String response = http.getString();
    Serial.println(response);
  }
  http.end();
}

Wifi connection was successful. But in my serial terminal I always see -1. I am using PlatfromIO in Visual Studio code.

Update 1: The URL was corrected.

 http.begin("https://calm-falls-41696.herokuapp.com/api/v1/cards.json");

I tested it with google.com too. But it is still returning -1.

As Musa said, I needed to suply the website certificate footprint to http.begin.

void loop() {
  HTTPClient http;
  String thumbprint="08:3B:71:72:02:43:6E:CA:ED:42:86:93:BA:7E:DF:81:C4:BC:62:30";
  String path = "https://calm-falls-41696.herokuapp.com/api/v1/cards.json";
  http.begin(path, thumbprint);
  int httpCode = http.GET();
  Serial.println(httpCode);
  if(httpCode == HTTP_CODE_OK) {
    Serial.print("HTTP response code ");
    Serial.println(httpCode);
    String response = http.getString();
    Serial.println(response);
 }
  http.end();
  delay(1000);
}


How to set "IPAddress ip" using a variable? Created a "variableInput.h" file for editing variables in one place; instead of searching multiple lines of code, to find lines needing editing.

//   variableInput.h
//
//   User defineable variables; one location for editing variables

// Replace with your network details
#define host = "esp32"
#define ssid = "YOURSSID"
#define password = "YOURPASSWORD"

//NTP Time Servers
#define udpAddress1 = "198.50.238.156"  //NTP Time server
#define udpAddress2 = "132.163.96.3"  //NTP Time server

//publicIP accessiable over Internet with Port Forwarding; know the risks!!!
//WAN IP Address.  Or use LAN IP Address --same as server ip; no Internet access.
#define publicIP = "YOURPUBLICIP"
#define LISTEN_PORT  8030  //default listening Port 80 for "GET" requests.

//Graphing requires "FREE" "ThingSpeak.com" account..
//Enter "ThingSpeak.com" data here....
//iframes of graphed data are available from "ThingSpeak.com."
#define myChannelNumber = 123456
#define myWriteAPIKey = "E12345"

//FTP Credentials
#define ftpUser = "FTPUSER"
#define ftpPassword = "FTPPASSWORD"

//setting the addresses
#define ip(10,0,0,200);
#define gateway(10,0,0,1);
#define subnet(255, 255, 255, 0);
#define dns(10,0,0,1);

//Restricted access to client ip list.
#define Restricted = "/ANYNAME"

//OTA Credentials
//default username: USERNAME
//default password: PASSWORD

// "setting the addresses" is the part that I do not understand.

Segment of related code from "wifi_Start" function:

//setting the addresses
IPAddress ip;
IPAddress gateway;
IPAddress subnet;
IPAddress dns;

Is there a solution?

William

Here's how I do it (for an Arduino that connects to my Mosquitto server) using wired ethernet (WiFi works the same way):

#include <Ethernet.h>
#include <PubSubClient.h>
EthernetClient ethClient;
PubSubClient client(ethClient);

byte mac[]    = {
  0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe
};
IPAddress ip(192, 168, 1, 75);
IPAddress server(192, 168, 1, 11);
void setup() {

  client.setServer(server, 1883);
  client.setCallback(callback);

  Ethernet.begin(mac, ip);

}


avrdude: stk500v2_ReceiveMessage(): timeout with ADDAC VCC I am getting the above error message uploading the ADDAC VCC, and the only thing that's changed I think is the patch is bigger.

Is there a fix for this or will I have to send it back? Hope my formatting is OK

Binary sketch size: 12,330 bytes (of a 258,048 byte maximum)
/usr/share/arduino/hardware/tools/avrdude -C/usr/share/arduino/hardware/tools/avrdude.conf -v -v -v -v -patmega2560 -cwiring -P/dev/ttyUSB0 -b115200 -D -Uflash:w:/tmp/build953252908946386724.tmp/comps.cpp.hex:i
avrdude: ser_recv(): programmer is not responding
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: Send: . [1b] . [01] . [00] . [01] . [0e] . [01] . [14]

avrdude: Version 6.0.1, compiled on Oct 21 2013 at 17:07:18
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/usr/share/arduino/hardware/tools/avrdude.conf"
         User configuration file is "/home/luke/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyUSB0
         Using Programmer              : wiring
         Overriding Baud Rate          : 115200
avrdude: wiring_open(): releasing DTR/RTS
avrdude: wiring_open(): asserting DTR/RTS
avrdude: Send: . [1b] . [01] . [00] . [01] . [0e] . [01] . [14]
avrdude: ser_recv(): programmer is not responding
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

avrdude done.  Thank you.

avrdude: ser_recv(): programmer is not responding
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: Send: . [1b] . [01] . [00] . [01] . [0e] . [01] . [14]
avrdude: ser_recv(): programmer is not responding
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: Send: . [1b] . [01] . [00] . [01] . [0e] . [01] . [14]

Your log is showing that communication is failing right away (avrdude never gets a proper response). This can mean that

the VCC is not resetting
there is no bootloader installed
there is some other defect

You can test case is by manually hitting the reset switch around the time that avrdude starts. If the necessary pins are available, you can exclude case 2 by installing a new boot loader with a programmer, which also tests scenario 3 a bit.


Send AT commands programatically to ESP8266 without Arduino Let me explain my question in more details. I want to use ESP8266-01 as standalone micro-controller for my project. I don't want to use Arduino or any other board with that.
Using Arduino i can use two of the pins as software serial and can send different AT commands to ESP module to ESP's Tx and Rx pins, but now what I want is to eliminate the need to Arduino.

What I want to do is to to program ESP itself to toggle mode from AP mode to Host mode on press of a push button. for that I has to send AT commands to ESP from the code while i will write to the ESP itself. Is there any way to achieve the same.

I tried searching a lot but what I found everywhere is how to send AT commands from Arduino.

Thanks in advance.

You don't use AT commands. You install the esp8266 boards package and program the esp8266 as if it were an Arduino. That means learning the esp8266 WiFi API which has plenty of examples included.

https://github.com/esp8266/Arduino/


Solar Power Inside a Car I plan on making an Arduino project for reminding a parent to take a child from a car. In order to power the project I though on using a solar panel. Since I can't rely on having solar power all the time I'll need to use rechargeable batteries and charge them with the solar panel.

The problem is that from reading about the subject it is clear that it can be dangerous as far as battery go up in flame in some cases, especially due to high heat.

My car can get into very high temperature when parked outside so this scenario is very likely to happen.

Can someone please direct me to reading materials about using solar power in a very safe way?

Firstly, solar panels inside a car is pretty pointless. Solar panels need to be in direct sunlight to be effective. Having them inside a car means they're not going to be in direct sunlight, so they're not going to be able to generate anywhere near enough power - unless they are massive, in which case where is the child going to sit? Yes, you could put them on the roof, but that would be silly.

The whole concept of solar panels for this project is completely wrong.

The car has a big battery and an in-built generator. Use them. There is absolutely no reason for you to have your own batteries as well. Yes, you could charge your own batteries from the car's battery, but that just introduces extra losses and wastefulness.

The only possible benefit of having your own batteries is it will safeguard the car's battery when the engine isn't running. It would then be impossible for your project to flatten the car's battery. But if you design your project properly that wouldn't be a problem anyway.

Some things you seem to be missing with your project:

The car has power you can use. It's throughout the car. No need to provide your own external power source.
The car has an "accessory" signal that is only turned on when the ignition is on. It's used by things like the radio etc so that when you turn the car's ignition off the radio turns off. No need for vibration sensors or anything to know if the car is running, it can tell you directly.
Cars generally have "seat occupied" sensors in them that couple with the seatbelts to know if a passenger hasn't got their seatbelt on and warn the driver (in most jurisdictions it's the responsibility of the driver to ensure all passengers have their seatbelts on).

If you really must charge batteries there are certain safety aspects you really must take into account. Your charge circuit must be able to manage the battery charging 100% safely. You have mentioned heat, and that is a very very important thing to manage. A decent battery manager chip will include an input for a thermistor. That is used as one of the multiple methods of charge termination (there's dv/dt (change in voltage over time), dT/dt (change in temperature over time), etc). It also serves as an over-heat safety cutout. Ensure that the charge circuit you use not only provides a thermistor input but also has the ability to cut off charging in the case of an overheat situation.

You also need to consider over-voltage. A car's 12V supply isn't 12V. It can get as high as 16V sometimes, and noise from the ignition can cause regular spikes as high as 70V or more. Automotive electronics have to be able to withstand those spikes, and that means your charge circuit has to be able to withstand those spikes.  Buffering the 12V through a proper 5V (cigarette lighter USB charger) regulator will remove that noise and make your circuit easier to work with.

So you need to think more carefully about just what it is you want to achieve and how that is going to fit into an automotive situation.


Arduino GSM Shields stacking I'm researching options for a project in which I need to send/receive SMS messages to/from multiple users of different service providers.
Hoping to reduce costs, I'm thinking of forwarding the messages to a different SIM card, depending of the user's service provider (since all of them have plans with free SMS for numbers of the same provider).
Arduino GSM Shield seemed like a good option, except the shield has only one SIM card slot.
I wonder: would it be possible to stack 3 shields (there are 3 mayor service providers in my country) on the same Arduino Board and use some reasonably straightforward programming to handle the task?
Thanks in advance.

Hardware-wise this should be pretty easy to do. You need to connect pins 2 and 3 of each GSM shield to separate serial ports on the Arduino board. The best way to do this is to use an Arduino Mega, which has 4 hardware serial ports, this leaves you Serial for uploading sketches and communication to Serial Monitor. It's also possible that you could use a software serial library like AltSoftSerial but I wouldn't recommend it. You can carefully bend the pins 2 and 3 of two of the shields out before stacking them and then use jumper wires to connect those pins to the hardware serial pins of the Mega. The other pin of interest is pin 7, which is the modem reset pin. If you leave all the modems connected to pin 7 on the Arduino that means that there is no way to only reset a single modem. I'm not sure how much of an issue that would pose. So you might be better off to bend pin 7 on two of the shield out also and connect those to separate pins. You will also need to be sure to provide a power supply capable of supplying sufficient current. The product page says each shield may require up to 1000mA.

Software-wise it gets much more tricky. Unfortunately the stock Arduino GSM library was not written to be very flexible. Instead of allowing you to pass it a Serial object it's hardcoded to do software serial on pins 2 and 3 so you would need to do quite a bit of work on the library to make it work for your needs. I'd recommend looking around to see if a more suitable library exists.


High frequency audio sampling and storage I want to use an arduino duemilanove atmega168 for audio signal processing. I can sample the signal at around 38.5kHz using this code. I want to send the sampled data over the serial to a computer for processing.

Data acquisition rate: 38.5 kbps (using 8-bit precision)
Maximum serial communication rate: 115200 bps (I don't know exactly how this relates to the transfer rate of the actual data (without any overheads), but anyhow the limit is 13.94 kbps)
Arduino flash memory: 16 kB

I would like to transmit around 4-5 seconds of the audio signal to the computer. Is there a way to achieve this?

After doing some reading here Serial.begin(): Why not always use 28800? and looking at the manual for the 168. You should be able to achieve the baud rate you want by directly programming the USAR.

According to the answer there you should be able to use miniterm to keep up with a high baud rate.

As stated there you might run into problems with computer power.

Read chapter 20 here http://www.atmel.com/images/doc2545.pdf.

Basically you can set up the USART speed (UDR0) and the control registers (UCSR0A,UCSR0B and UCSR0C) such that you can send data pretty fast.

Let me know if you can't access that link and if you need me to explain some more about these things.


Data packet format when USB initialized as COM port Does anyone know how the data in data packet looks like when the USB is initialized as COM port?

I have a Arduino Mega 2560. I have initialized COM port with a baud rate of 9600. I know that there are four types of USB packets as

Token Packet (Commonly used for device identification and transaction initiation.)
Data Packet (Contains the data that needs to be transferred from host to client or vice-versa.)
Acknowledgement Packet (Acknowledgement for error-free data reception.)
Special Packets (Hub to hub communication and speed differential.)

The payload in data packet is formatted as

DATA1 >> PAYLOAD >> CRC16 ; DATA2 >> >> PAYLOAD >> CRC16 ; etc.

Till this point I am clear about whats happening.

Now all I want to know is

How the data is structured in the PAYLOAD section, when USB is initialized as COM port?
How the baud rate comes into picture i.e how a particular baudrate is achieved in this type of communication?
How is communication in terms of packet sequence? Does the sequence of packets change? (Like token>>data>>ack>>data>>ack>>...)

I really need to know this urgently as I am working on program that has to connect with 3 MEga2560 boards through a USB hub. I want to fix my design constraints depending on what is the maximum baud rate that I can achieve for all boards.

Once the USB connection is initialized as a COM port, it no longer utilizes traditional USB packets (only internally). It acts as a regular COM port. This layer of abstraction is created by 8u2 chip on Arduino side and by the driver on the PC side.

If you need to use the USB without the COM port abstraction, you have to probably configure the 8u2 chip to behave this way. I think it should be possible to configure to act as some HID device for example. You would also need to take care about the PC side and you might have to write your own driver.

For a guide on hacking and configuring the 8u2 chip on Mega, see following link:

http://arduino.cc/en/Hacking/DFUProgramming8U2


Thermistor returns correct value on Arduino Nano, completely fails on Arduino Uno Wifi Rev 2? I am completely baffled. When I wire the thermistor into my Nano, everything reads completely fine. Then when I switch to the Uno Wifi Rev 2, I get negative numbers -40 to -80 when I was reading 24 on the Nano.
Wiring Diagram is:
           Thermistor
           |       |
Gnd---Resistor     Vcc
           |
       A6/A0 (6 for nano, 0 for Uno)

Code is:
#include <thermistor.h>
#define pin A6 //I change this to A0 on the WIfi. This is the only change
float temp;
uint32_t timeout = millis();
THERMISTOR thermistor(pin, //Analog pin
                  9800,    //Nominal res at 25 ºC
                  3559,    //Thermistor's B value
                  10000);  //Value of the resistor
void setup() {
  Serial.begin(9600);
}

void loop() {
  delay(1000);
  temp = thermistor.read();
  Serial.println(temp);
}

The Arduino UNO WiFi Rev2 defaults to an internal analog reference of 0.55V where the classic (non-"Every") Nano defaults to the external VCC voltage as a reference, which is usually around 5V, often a little lower because of the diode it uses between USB and "5V".
Either you need to be using the same voltage reference by selecting a common one with analogReference, or you need to use different references and calculate differently (or provide different values to the thermistor library) according to each reference.
If you've been using the VCC on the normal Nano board, you could try analogReference(VDD); on the UNO Wifi Rev 2.  This isn't necessary a great way to do it (probably using internal references would be better), but it is a simple way to get similar results on a UNO Wifi Rev2 without changing more than a single line to set the reference.


Arduino bluetooth HC-05 data reading problem I have a problem with bluetooth module HC-05 and servos. If I type in bluetooth terminal 4,1 I want that servo1 turns 60 degrees 3 times. Briefly servo1 turns 60 degrees and then servo2 goes 180 and turns back and again servo1 turns 60 degrees and so on.

The bluetooth mixes the numbers. If I type "1" it gives me "49" and that's why the system is not working properly. How do I fix this data problem?

#include <Servo.h>
#include <SoftwareSerial.h>

Servo myservo1;
Servo myservo2;
long players, cards;
int pos1 = 0;
int pos2 = 0;
int servo;
int pos = 0;
int deal = 0;

SoftwareSerial BT(2,3);

void setup() {
  Serial.begin(9600);
  BT.begin(9600);
  myservo1.attach(10);
  myservo2.attach(11);
  servo = 90;

}

void loop() {
  if(BT.available()>0) {
    players = BT.read();
    cards = BT.read();

    Serial.println(players);
    Serial.print(cards);

    pos = 180/(players-1);
    for(deal = 0; deal < cards; deal++) {
      for (pos1 = 0; pos1 <= 180 ; pos1 += pos ) {
          delay(20);
          myservo1.write(pos1);

          for (pos2=0; pos2<=180 ; pos2 +=1){
            myservo2.write(pos2);
            delay(10);
          }

          for (pos2=180; pos2>=0 ; pos2 -=1){
            myservo2.write(pos2);
            delay(15);
          }

    }
      for (pos1 <= 180; pos1 >= 0; pos1 -=1 ) {
          pos2=0;
          myservo1.write(pos1);
          delay(10);
      }
    }

  }
}

You are mixing ASCII characters and integer values.

The serial data is a pure binary stream, a series of bytes. It is up to the programs on both sides to interpret, how these bytes are meant. When you type 1 into your bluetooth serial app, it already does this. It complies to the ASCII standard, which gives a meaning to every binary value between 0 and 127. Google "ASCII" to get a table of the mapping. Each character (alpha numeric and some special characters and control characters) has a binary value associated with it. That way we can interpret a binary data stream as text.

The ASCII character 1 corresponds to the decimal value 49. You are saving the read byte from the bluetooth serials as long, which is a big integer. So, when you are printing it, you will see the decimal value, which is 49.

What to do now? The easiest way is to subtract the ASCII value of '1' from the received byte:

players = BT.read() - '0';

'0' is the C/C++ representation of a single ASCII encoded character. It's the same as subtracting the decimal value 48, but it's a bit clearer to see, what happens here. We are shifting the numbers row (0 to 9) from position 48 to position 0. That way the ASCII '0' is transformed to a decimal 0, the ASCII '1' to a decimal 1, and so on up to 9.

Note: You might want to make sure, that only numbers are used for these variables, as the principle will result in garbled data, when the user inputs some other characters. You would need to read the binary data into a temporary variable (here called c) and then check, if they are numeric. Either by hand:

if(c >= '0' && c <= '9')

or by a convinient function

if(isDigit(c))


How does an 8bit MCU make use of data-types over 8bits? how does an 8bit MCU handle 16bit output?
How does an 8bit MCU store values higher than 8bits?
I am using an attiny, on an adafruit trinket. and other 8bit MCUs.
http://www.atmel.com/devices/attiny85.aspx
I was doing some things with uint32_t datatypes, when it hit me, that it would seem like uint32_t would be an incompatible datatype. Even 2Byte data type like int seems peculiar. "int stores a 16-bit (2-byte) value"
considering the MCU is 8bit.

I saw this link, that sounded like it would have more info, but its pages are incomplete. http://playground.arduino.cc/Code/DatatypePractices

So how does that work?
How does an 8bit MCU make use of data-types over 8bits?

The basic answer is that the processor does math in 8-bit chunks, so it takes more instructions than it would on a 32-bit processor.

A good answer is found in EE.SE


Why does my 16x2 LCD displays weird letters and can't insert key from keypad? I'm a newbie on Arduino here, and this is my first project on 16x2 LCD, 4x4 keypad and others. So, the story is, after I uploaded the program for my group's Arduino alarm clock to the Arduino board, the LCD displays black boxes on the first row of the LCD. But after soldering the LCD pins again and connect the Vo to the 10k ohm potentiometer, the LCD can display the "welcome" part properly. This can be seen in the two pictures below.

However, after a while, there are weird letters appearing on the second row of the LCD, blinking from the first picture below to the second picture again and again. Plus, I couldn't input any key from the keypad to the LCD, since the display's stuck at there.

I'm not sure if there's any problem in the circuit or in the programming. I'm quite confused here. Below is the code I uploaded to the Arduino board. Thank you in advance.

#include <EEPROM.h>
#include <Keypad.h>
#include <DS1307.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <LiquidCrystal.h>

DS1307 rtc(SDA, SCL);
LiquidCrystal lcd(A3, A2, A1, A0, 5, 4);
Time t;

#define buz 3

int Hor, Min, Sec, h, m, s;
int ASCII = 48;
char* tim;
char* dat;
const char key = 0;
char buffer[2];
const byte numRows= 4;
const byte numCols= 4;
char keymap[numRows][numCols]=
{
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};
byte rowPins[numRows] = {12, 11, 10, 9};
byte colPins[numCols]= {8, 7, 6, 5};
Keypad myKeypad= Keypad(makeKeymap(keymap),rowPins, colPins, numRows, numCols);

void setup() {
  Wire.begin();
  rtc.begin();
  pinMode(buz, OUTPUT);
  lcd.begin(16, 2);
  welcome();

  rtc.setDOW(SATURDAY); //Set Day-of-Week to SUNDAY
  rtc.setTime(10, 54, 0); //Set the time to 12:00:00     (24hr format)
  rtc.setDate(7, 1, 2017); //Day, Month, Year
}

void loop() {
  t = rtc.getTime();
  Hor = t.hour;
  Min = t.min;
  Sec = t.sec;
  tim = rtc.getTimeStr();
  dat = rtc.getDateStr();
  char key = myKeypad.getKey();

  if (key == 'C'){
    digitalWrite(buz, LOW);
    EEPROM.write(2, ASCII+6);
    EEPROM.write(3, ASCII);
  }

  if(key == '#'){
    lcd.setCursor(0,0);
    lcd.print("Enter New Time");
    lcd.setCursor(0,1);
    int j =0;
    int i=0;
    while( j<6)
    {
      if(i==2 || i == 5){
        lcd.print(":");
        lcd.display();
        i++;
      }
      key=myKeypad.getKey();
      if(key)
      {
        lcd.print(key);
        lcd.display();
        EEPROM.write(j,key);
        j++;
        i++;
      }
    }
  }

  changealarm();
  checkalarm();
  timedate();
}

void checkalarm(){
  if( Hor == h && Min == m)
  {
    delay(3000);
    lcd.setCursor(0,1);
    lcd.print("Hold C");
    digitalWrite(buz, HIGH);
    delay(3000);
  }
}

void changealarm(){
  buffer[0]=EEPROM.read(0);
  buffer[1]=EEPROM.read(1);
  h = atoi(buffer);
  buffer[0]=EEPROM.read(2);
  buffer[1]=EEPROM.read(3);
  m = atoi(buffer);
  buffer[0]=EEPROM.read(4);
  buffer[1]=EEPROM.read(5);
  s = atoi(buffer);
}

void timedate(){
  lcd.setCursor(0,0);
  lcd.print("Time: ");
  lcd.print(rtc.getTimeStr());

  lcd.setCursor(0,1);
  lcd.print("Date: ");
  lcd.print(rtc.getDateStr());
  delay(3000);
  lcd.setCursor(0,1);
  lcd.print("Alarm: ");
  lcd.print(h);
  lcd.print(".");
  lcd.print(m);
  lcd.print(".");
  lcd.print(s);
  delay(3000);
}

void welcome(){
  lcd.setCursor(0,0);
  lcd.print("Welcome");

  lcd.setCursor(0,1);
  lcd.print("To");
  delay(3000);

  lcd.setCursor(0,1);
  lcd.print("TIMeProject");
  delay(3000);
}

In your changealarm() function, you call atoi(buffer), and buffer is defined as char buffer[2].

atoi() expects a c-style string, which is null-terminated, and you have to include space for the null termination character ('\0', 0, 0x00, etc.), but you write to both allocated spaces in the changealarm() function. If your 2nd byte of each EEPROM space (1, 3, 5) is non-zero, then your have an unterminated string.

atoi() expects a null-terminated string, and so the behavior is unexpected. Probably atoi() is running into other memory. If the string being sent is not representable by a int type, then the behavior of atoi() is undefined.

A quick fix would be to increase the size of buffer and guarantee null termination:

char buffer[3];  // Make the buffer 3 bytes long
[...]
void changealarm() {
  buffer[2]=0;   // Set the 3rd byte to zero to null-terminate

  buffer[0]=EEPROM.read(0);
  buffer[1]=EEPROM.read(1);
  h = atoi(buffer);
  buffer[0]=EEPROM.read(2);
  buffer[1]=EEPROM.read(3);
  m = atoi(buffer);
  buffer[0]=EEPROM.read(4);
  buffer[1]=EEPROM.read(5);
  s = atoi(buffer);
}


Turning all LEDs on (FAST.LED) In Fast.Led lib for arduino there is a code to turn off all leds

FastLED.clear ();

Is there also a shortcut to turn all LEDs ON, and with a specific color

You can use fill_solid.

For example

fill_solid( leds, NUM_LEDS, CRGB(50,0,200));

Or

fill_solid( leds, NUM_LEDS, CRGB::Red);


How to add the -F switch for avrdude in Arduino IDE So, before starting to learn with something else, I'll give it one last try. The avrdude is complaining that the device signature doesn't match. Whatever, I don't care. To me, what's written on it is what counts.

So I'd like to force it to upload the program. It promises to ignore the problem if -F is specified.

Where are settings for avrdude parameters, like other IDEs have settings for their compilers?

The error probably means that you have selected a wrong configuration.

To modify the IDE to insert the -F seems to be the hard way,
however the easy way is to make a wrapper to avrdude:

$ cd ./arduino/hardware/tools/
$ mv avrdude avrdude.orig
$ cat >avrdude.sh
  #!/bin/sh

  ./avrdude.orig -F $@
  ^D
$ chmod +x avrdude.sh
$ ln -s avrdude.sh avrdude


Looks like a smartwatch but only has a gps tracker and password I was wondering if anyone had any suggestions about my idea. I want to crate something like a smartwatch but all I need it to have is a Gps and aa password. I want to be able to track it with a smart phone. Finger print would be awesome too

So basically what you want is a GPS-Receiver(-Shield), a SIM900(-Shield), a Fingerprint-Sensor, a Battery-Pack and a micro-controller. (And of course some kind of server)

Have you made some research for the parts you want to use and considered their size and power consumption? Sounds completely feasible but your Arduino Prototype will look like it fits into a lunch-box. The idea is a good one and worth trying. (albeit I don't know what the password/fingerprint is good for).

But you will have trouble to shrink it into the size of a smartwatch.


GSM Modem with MAX232 to Arduino Serial? I have GSM modem that has MAX232 interface for RX/TX/GND on three pins.
Is it possible to interface Arduino in some way?

Tnx for help.

Yes, with another MAX232, or bypass the MAX232 somehow.


How to control a DSP-G1 programmatically/electronically? I want to generate music/sounds for a video game I am making with my son (using an Arduino Mega and a 240x320 LCD graphical display). I have a basic understanding of the MIDI protocol. I've been a computer programmer for over 30 years. I read the MIDI implementation in the DSP-G1 manual, but I don't understand how to go from this to sending the right signals from the dev board to the chip pins.

Everything I find is about connecting a physical MIDI device. Can anyone possibly provide or point me to information on how to control the DSP-G1 programmatically/electronically? I think I need some hardware or software to serialize MIDI protocol bytes into a sequence of voltage changes, but all my searching leads me to info about a physical device.

The purpose of the MIDI output circuit is to convert the TTL signal into a 5 mA current.
The purpose of the MIDI input circuit is to convert the current back into a TTL signal.

If the Arduino and the DSP-G1 are part of the same circuit (and share the ground), you can omit these conversions, and connect the Arduino's TX directly to the LPC810's RX, without any other components needed. (The LPC810 requires a 3.3 V power supply, but its RX pin is 5 V tolerant.)

MIDI was designed to work with most microcontrollers, so it uses standard UART signals at 31250 baud. The only configuration you need is:

Serial.begin(31250);


How do I adjust the scale/calibration of a photoresistor? This photoresistor has a min/max of 0-1023.

I'm trying to scale the brightness of a cathode RGB LED based on the sensor's value, but based on my current lighting, the min/max readings I generally am getting are 100-700.

So how can I scale the sensor reading so that 100 = no light on the LED and 700 = max brightness?

You can easily scale in Arduino code with the map() function.

e.g.:

const int MIN_LIGHT 100;
const int MAX_LIGHT 700;

int light_reading = analogRead(A0);

// Convert MIN reading (100) -> MAX reading (700) to a range 0->100.
int percentage_bright = map(light_reading, MIN_LIGHT, MAX_LIGHT, 0, 100);

But you may need some calibration of your system to handle different ambient light situations. What reading do you get in direct sunlight for example?

So then I assume you're using PWM (Pulse Width Modulation) to drive the LED.  This requires a value between 0 & 255.  Once again we can use the map() function.

// Convert light-value % (0-100) to PWM speed (0-255)
int led_brightness = map(percentage_bright, 0, 100, 0, 255);
analogWrite(LED_PIN_RED, led_brightness);

Obviously these bits of code can be reduced down to a single line - mapping directly from the reading to the desired result.


ESP8266 not connecting to WiFi I am trying to send the temperatures from an DS18B20 to ThingSpeak, using an ESP8266. You can see the code I am using for that.

When I run the code I do not get any errors. In serial monitor it just shows that it is not connected to WiFi. If I change the WiFi name in code to something not even existing I still do not get any errors. I do not think that the ESP even finds the WiFi.

I think that the only problem to get everything work is just to get the WiFi connection to work properly. I have also checked the ESP with another simple code just to check that it is not broken and it actually get the code from my computer.

Here is the code I am using. (I have removed my password etc... )

//nodeMCU v1.0 (black) with Arduino IDE
//stream temperature data DS18B20 with 1wire on ESP8266 ESP12-E (nodeMCU v1.0)
//shin-ajaran.blogspot.com
//nodemcu pinout https://github.com/esp8266/Arduino/issues/584
#include <ESP8266WiFi.h>
#include <DallasTemperature.h>
#include <OneWire.h>

//Def
#define myPeriodic 15 //in sec | Thingspeak pub is 15sec
#define ONE_WIRE_BUS D4  // DS18B20 on arduino pin2 corresponds to D4 on physical board
//#define mySSR 0  // Solid State Relay on pin 0

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature DS18B20(&oneWire);
float prevTemp = 0;
const char* server = "api.thingspeak.com";
String apiKey ="******";
const char* MY_SSID = "******";
const char* MY_PWD = "******";
int sent = 0;

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

void loop() {
    float temp;
    //char buffer[10];
    //DS18B20.requestTemperatures();
    //temp = DS18B20.getTempCByIndex(0);
    temp=1111;
    //String tempC = dtostrf(temp, 4, 1, buffer);//handled in sendTemp()
    Serial.print(String(sent)+" Temperature: ");
    Serial.println(temp);

    //if (temp != prevTemp)
    //{
    //  sendTeperatureTS(temp);
    //  prevTemp = temp;
    //}

    sendTeperatureTS(temp);
    int count = myPeriodic;
    while(count--)
    delay(1000);
}

void connectWifi()
{
    Serial.print("Connecting to "+*MY_SSID);
    WiFi.begin(MY_SSID, MY_PWD);
    while (WiFi.status() != WL_CONNECTED) {
        delay(1000);
        Serial.print(".");
    }

    Serial.println("");
    Serial.println("Connected");
    Serial.println("");
}//end connect

void sendTeperatureTS(float temp)
{
    WiFiClient client;

    if (client.connect(server, 80)) { // use ip 184.106.153.149 or api.thingspeak.com
        Serial.println("WiFi Client connected ");

        String postStr = apiKey;
        postStr += "&field1=";
        postStr += String(temp);
        postStr += "\r\n\r\n";

        client.print("POST /update HTTP/1.1\n");
        client.print("Host: api.thingspeak.com\n");
        client.print("Connection: close\n");
        client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
        client.print("Content-Type: application/x-www-form-urlencoded\n");
        client.print("Content-Length: ");
        client.print(postStr.length());
        client.print("\n\n");
        client.print(postStr);
        delay(1000);

    }//end if
    sent++;
    client.stop();
}//end send

Maybe you have a space in your WIFI SSID so you should check this in your router. Also maybe your WIFI is on 5Ghz and the ESP can't see it because it is only for 2.4 Ghz. Also if your WIFI AP is on a channel from 13 - 14 it also couldn't be seen by the ESP. And to test your ESP you can run the scan example and if it works you should try the web server example to connect to your network. If that all will work ok than the problem is in your code.


Conflict between OneWire and I2C? I have two Arduino boards and I want to make them communicate via I2C. The first board (slave) should read a temperature value from a DS18B20 sensor (OneWire) and send it to the second board (master) via I2C.

So, I tried to merge some code from the standard examples (Wire/master_reader, Wire/slave_sender and dallas/simple).

When I use the two sketches bellow, the serial monitor of the master board is printing the "hello " message, but when I enable the request temperature lines (slave code)

sensors.requestTemperatures();
sensors.getTempCByIndex(0);

the serial monitor shows nothing.

I wander if there is a conflict between OneWire and I2C, or if I've made some serious mistakes in the code.

Any suggestions would be appreciated.

Master

#include <Wire.h>

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

void loop(){
    Wire.requestFrom(2, 6);
    while(Wire.available()){
        char c = Wire.read();
        Serial.print(c);
        }
    delay(500);
   }

Slave

#include <Wire.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

void setup(){
    sensors.begin();
    Wire.begin(2);
    Wire.onRequest(requestEvent);
 }

void loop(){
}

void requestEvent(){

    //sensors.requestTemperatures();
    //sensors.getTempCByIndex(0);

    Wire.write("hello "); // respond with message of 6 bytes
}

The OneWire stuff can be quite slow. I think I timed doing a temperature read at 12.5 mS which is a long time to be in an ISR. I think you will find that the master assumes it is going to get no response and times out, in that time.

1-Wire Peripheral Interface - for Arduino

What I suggest you do, is get the temperature in the slave, as often as you want, and then just return the temperature when requested. eg.

volatile float lastTemp;

void loop(){
  sensors.requestTemperatures();
  float t = sensors.getTempCByIndex(0);
  // protect move of 4 bytes
  noInterrupts ();
  lastTemp = t;
  interrupts ();
}

void requestEvent(){
  Wire.write ((char *) lastTemp, sizeof lastTemp);
}

Untested, but that is the general idea.

Documentation about interrrupts, and why I am turning off interrupts when moving the temperature to a global variable: http://www.gammon.com.au/interrupts


arduino pro mini downloading? I purchased the arduino pro mini atmega328 and equipped it with FTDI breakout board with USB, a battery charging board, Wireless transmitter and a wireless receiver.  I'm assuming they can all be connected.  My question is, how do I download programs to the arduino board?  And where might I find specific programs to download?

The Arduino Pro Mini has a row of connections at the small end that align with the connections on the USB-to-Serial board you have.  They are marked GND - VCC - RXI - TXI and should be in the same order as the connector on the FTDI board. I think that the pin marked GRN on the Arduino will align with the connector marked DTR on the USB-to-Serial board, but please make sure that VCC aligns with 5V!

With the FTDI board plugged into the Arduino, you can plug your computer into the FTDI board's USB port and when you run the Arduino IDE programming tool, that USB port should say that it's connected to a serial port.  Pick the "Arduino Pro or Pro Mini" as your board, then pick your processor (most likely the "ATmega328 (5V, 16MHz)" and finally your port (that serial port you found).

Now when you upload your Arduino program to the Arduino, it will know the board your have and the port to use.

As for programs to use, start simple and get the onboard LED to blink.  From there, you'll have the basics down for creating a program and getting it to the Arduino.  You'll find tons of example programs (called sketches in Arduino land) that will help you connect all your fun wireless gizmos!

As noted above - Google is your friend.  There are many places to go for examples and help.  Start with some of the commercial sites like Adafruit and SparkFun. Their staff really supports the Arduino community with how-to videos, libraries, examples, etc.


Is the analogread function averaging the samples taken by the ADC? In many development boards the analog voltage data which is sampled by the ADC can be sent to the serial port. But the data speed I see on the serial port by HyperTerminal or Serial monitor is much slower than the sampling rate.

Lets take Arduino as an example. As far as I understand the analogread() function samples an analog input at 10kHz rate. It means 10000 samples taken per second.

But when I use the Serial Monitor it seems the data speed which we see as upcoming/flowing line by line per second on Serial Monitor is much slower.

Is that because the analogread() is averaging the samples before the data is sent to the serial port?

As far as I understand the analogread() function samples an analog input at 10kHz rate.

No, it samples an analog input at once per invocation. This means that if it is run 10000 times within a second (assuming it can be run that many times within a second) then the code is sampling at 10kHz. But if it's run only twice per second then the code is sampling at 2Hz.


Sending multiple byte data from Arduino as Slave on SPI I have been working around the teardown of an induction cooktop and thought of having a tweak in the system. So far, I have deduced following circuitry out of the cooktop-
There are two devices communicating with each other in 3-wire SPI mode. The master, which controls power management and Induction circuitry, continuously sends commands and data to the slave. The slave, which is TM1628, receives the master commands and data, then accordingly displays the data on the seven segment or responds with the switch pressed, if any.

The above picture explains it better. Now, I thought of replacing TM1628 with an Arduino. So far so good. I gathered all the data that was being sent by the master and the reply sent by the slave.

But, when I started to code, I got stuck in one place. So the data as sent by the master and its response looks like this -

(Master to Slave)**Command1 - Command2 - Data1 - Data2 - ... - Data 14 - Command1 - Command2 - **(Slave to master)**Data1 - Data2 - ... - Data5 - **(And now the repetition)

When the master is sending the data, I have no issues as the data will continuously be read by Arduino and I can take the action accordingly.
But when the Arduino (Working as a slave) needs to send continuously 5 streams of data, depending only on the clock input timing from the master, how could I know that one stream has been written and now the next data has to be written to the SPDR register.

With SPI there is no such thing as "sending" and "receiving".  It is a full duplex operation every time. Whenever the master runs the clock the slave both receives bits from the master and simultaneously sends bits to the master.

These operations are inseparable.

Whatever mechanism you are using to recognise "A byte has arrived from the master" is the same mechanism that you use for filling the SPDR register. The bytes where you "send" data to the master are actually bytes where the master is sending you data, but you don't care about what that data is. Just like when the master is sending you "commands" you are sending the master data (which you haven't specified) and the master "doesn't care" what that data is.

It's up to you to keep track of how many bytes the master has clocked in and out, and to say "For bytes 19-23 the master is expecting valid data, so I need to make sure that I put data into the SPDR for those bytes".


Read sensor and convert reading to const char* I'm working on a home automation project using Arduino and MQTT.

I've found a problem and my limited programming knowledge find a way to solve it.

I can send text trough MQTT normally, using

client.Publish("some/topic","Some text here");

But when I try to send a variable (int, char, etc), the compiler says "invalid conversion from 'char' to 'const char*' [-fpermissive]"

How can I store DHT11 sensor reading in const char* to send it?

BTW, I've found this code where

char *tempC;
tempC = dtostrf(((((analogRead(tempPinIn) * 5.0) / 1024) - 0.5) * 100), 5, 2, message_buffer);
client.publish("arduino/temperature",tempC);

is used. But the extra sensor calibration makes it even harder for me to understand whats going on.

The function dtostrf() is prototyped as:

char *dtostrf (double          val,
               signed char     width,
               unsigned char   prec,
               char           *sout);

Where:
   val      Your float variable;
   width    Length of the string that will be created INCLUDING decimal point;
   prec     Number of digits after the deimal point to print;
   sout     Destination of output buffer;

An example of usage is as follows:

/* OPTION ONE */

    char msgBuffer[20];           // make sure this is big enough to hold your string
    char *pointer_to_created_string;

    float testFloat = 123.45;

    pointer_to_created_string = dtostrf(testFloat, 6, 2, msgBuffer);
    client.Publish("...topic...", pointer_to_created_string);

/* OPTION TWO */

    char msgBuffer[20];           // make sure this is big enough to hold your string

    float testFloat = 123.45;

    client.Publish("...topic...", dtostrf(testFloat, 6, 2, msgBuffer));

Don't be put off by the code in the link you included in your question. The first argument sent to dtostrf (everything before the first comma) is nothing more than a some calculations bundled into one single line.


How do I change the Console colour of Arduino IDE? Leading on from the question Can I change font Color and/or Type for IDE 1.5.6r2?, in 1.6.0, or 1.6.11 it does not seem to be possible to change console.color or console.error.color. To be precise, you can change the settings in the preferences.txt2 file, but they appear to be ignored when the IDE is restarted. Have these become hard coded?  I see from the preference.txt example file that

# Some colors have been hardcoded into the source in app/ in order to ensure
# consistency with the images distributed and stored with the application.
# They have been commented out below so that users who install an old
# version of the software will not get incorrect colors left-over from this
# config file.

However, the settings to which I refer are not commented out, and so would led me to believe that they can be changed. Orange text on black is just horrific to read.

For example:

console.error.color=#FFF000
console.color=#FFCCCC

but I still get white/orange(red?) text for the output and error messages respectively.

I am making the edits while the Arduino IDE is not running.

1 In 1.6.3 the ignored console.color etc. lines appear to have been removed from the preferences.txt file.

2 C:\Users\username\AppData\Roaming\Arduino15\preferences.txt

It turns out that the theme.txt configuration file is not located alongside the preferences.txt file, but alongside/under the Arduino application's .jar files. Thus, for the current version (1.6.3):

on OS X, .../Arduino-1.6.3.app/Contents/Java/lib/theme/theme.txt
on Win7, C:\Program Files\Arduino\lib\theme\theme.txt
on Linux, .../arduino-1.6.3/lib/theme/theme.txt
on Windows 10, when installed as an App, C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\lib\theme\theme.txt, however it does not seem possible to edit it - it can be opened in notepad++ but a save fails.

See an associated Github issue, IDE Background and print color options needed, for a little more discussion.


Arduino Nano ESP8266 software serial problems I have a problem with my Arduino Nano ATmega328 and my ESP8266 01 module. I have connected the ESP8266 on my Arduino board without FTDI.

I have made the following connection:

I an using a 5V Arduino Nano which of course is 5V. The ESP8266 is a 3.3V device and so I am using a voltage divider to bring the Arduino's 5V down to 3.3V. If you are using a 3.3V Arduino then you do not need the voltage divider.

The wiring is very similar to the FTDI.
Arduino pin 3 to voltage divider and then to ESP8266 RX
Arduino pin 2 to ESP8266 TX
Arduino GND to ESP8266 GND
Pull CH_PD HIGH with a 10K resistor to +3.3V
+3.3V to Vcc

You only need the voltage divider on the Arduino TX pin. The 5V Arduino will read 3.3V as HIGH so you can connect the ESP8266 TX pin directly to the Arduino RX pin.

The problem I had and I can't handle is that when I start up the Arduino Tx and Rx LEDs work continuously so I can't have access to my serial monitor of the Arduino IDE. So with that problem I can't send or receive any command to/from the IDE. Also when I try to upload my program to the Arduino board, I have to disconnect the ESP. If I don't I can't upload it.

Any ideas guys? I would be grateful

I also try to implement code with AltSoftSerial but I have library issues - my laptop does not recognize it (I downloaded it and I put it in the same folder with my code).

  #include <SoftwareSerial.h>

    SoftwareSerial ESPserial(2, 3); // RX | TX
    void setup()
    {    Serial.begin(9600);     // communication with the host         computer

     // Start the software serial for communication with the ESP8266
     ESPserial.begin(9600);

     Serial.println("");
     Serial.println("Remember to to set Both NL & CR in the serial monitor.");
     Serial.println("Ready");
     Serial.println("");}

     void loop()
      {
      // listen for communication from the ESP8266 and then write it to the serial monitor
       if ( ESPserial.available() )   {  Serial.write( ESPserial.read();}  / / listen for user input and send it to the ESP8266
      if ( Serial.available() )       {  ESPserial.write( Serial.read()  );  }}

Arduino Nano has its tx-rx serial port shared with the FTDI chip used by downloading and serial console. See https://www.arduino.cc/en/uploads/Main/ArduinoNano30Schematic.pdf
This means that if you drive these pins from ESP, it will flash leds, and all communication on these pins will interfere with serial monitor and board programming as well.

You may:

disconnect ESP during program downloading
pick a different board, which has a separate hardware serial port, such as Arduino Micro, Leonardo, or any Pololu A-star 32u4 boards, this way you have a dedicated serial port to control your ESP
wire the tx-rx of ESP to two other pins of your Arduino micro, and use a software serial library to bit-bang serial communication. (Note that serial receiving in software mode may require clever programming - since while your code does something else it can not receive anything).


Digital LED clock - matrix circuit question i'm making a digital clock.
Right now the plan is to matrix them on a atmega328 using transistors.
I figured i need a transistor on both sides or the current would be sinked/sourced by the atmega, which is not what i want.

I'd rather use the MAX7219 but i'm not sure if it's possible to use transistors, because i don't think the MAX7219 can handle the current.

I found the circuits here, i smushed them together, is this correct? Idk.

This is the led segment i'm using, there's four of them. So four 337 transistors, one for each digit. And seven 327 transistors, one for each segment.
I will scan through the four digits and turn on the apropriate segment.

So yea, please let me know if this is totally wacky or something else.

Edit :
I guess this would be 1 digit. Sorry it's confusing to draw the whole matrix. I hope this clears it up. It's just a normal matrixing situation but with more leds.

So normally it goes something like this :
The cathodes of the leds are controlled directly by the atmega, but results in the atmega supplying the current. So my reasoning would be to put a row of transistors there instead, would that be correct?

Since you're using a matrix of anodes and cathodes you need to connect/disconnect both ends of each LED.

You will probably multiplex these LEDs and only light one at a time. Are the LEDs high enough current that you can't either source or sink enough current for a single LED directly from Arduino pins? Most LEDs run on ≤ 20 mA, which an atmega328 can handle.

If you are trying to drive LEDs that need > 20mA then your plan to switch both the +5 and the ground with transistors should work. As StarCat said, you should consider the "on resistance" of your transistors as part of your calculation for the value needed for the current limiting resistors of your LEDs.


Giving the impression of a dying device - making a vibrating motor slow down and stop I'm trying to make a gag gift for a friend. The effect I'm trying to imitate is of a device that starts up for a moment and then putters out like something is wrong.

So I need it to:
1. Vibrate a motor for a second or two.
2. Make the vibration sputter out.
3. Light up an LED behind an error message on a paper screen.

I have very little hands on experience with anything electronic, but I have some programming and I took enough physics to know what a capacitor, etc is.

My questions are whether an Arduino is a good and cost effective way to accomplish this and is there any beginner friendly advice anyone can give me to get this accomplish

You can control the motor using PWM (Pulse Width Modulation) and make it run for full, then slowly decrease the speed till stop and after light up the led.
This tutorial from Adafruit could be a good start if you are not familiar with PWM and have also some good advices: https://learn.adafruit.com/adafruit-arduino-lesson-13-dc-motors/overview

Please be really careful about the supply source. Motors can easy draw more current then the limited available from the pins of arduino. Maybe a H-bridge could be helpfull here.(take a look at this for example of h-bridge: https://learn.adafruit.com/adafruit-raspberry-pi-lesson-9-controlling-a-dc-motor/lm293d )


Can anyone help be get readings off of my potentiometer with a push of a button? Hi I'm trying to get my Arduino Uno code to work with a in a specific way where if I push a button, the Arduino will read the raw potentiometer value once and if I don't push it nothing happens.
https://imgur.com/M7qGvtC
int switchState = 0
int switchPin = 2
int potPin = A0;

void setup() {
pinMode (potPin, OUTPUT);
pinMode (switchPin, INPUT);
Serial.begin (9600);

}

void loop() {
switchState = digitalRead(2);
if (switchState == High) {
Potval = analogRead(potPin);
Serial.print("potval:");
Serial.Println(Potval);
delay(200);
}

else {
(switchState == LOW);
while (Potval);
}
}

I had a very similar issue an it is that you aren't setting up your button as an INPUT_PULLUP. When you press the button, you are sending 5V or ground through it depending on your circuit. But then it won't reset on release. That is why either you can put a physical resistor as the schematic shows here:

or you can simply change the button initialization to INPUT_PULLUP.


Improper sampling of wave I am using Arduino Mega 2560 to sample and serially send a square wave. I am using Processing 3.3.6 for logging the data to .csv file. I am receiving about 6k samples at the moment. When I try sampling a square wave, min= 0V, max=3V at 200Hz, the number of samples at the two amplitudes(at 0 and 3V) are not at all close by. What could be going wrong?

This is my Processing code:

//import the required libraries
import processing.serial.*;

Serial mySerial;
Table table;
String filename;

void setup()
{ //print(0);
  //set mySerial to listen on COM port 4 at 1000000 baud
  mySerial = new Serial(this, "COM4", 1000000);

  table = new Table();
  //add a column header "Data" for the collected data
  table.addColumn("Data");
  //add a column header "Time" and "Date" for a timestamp to each data entry
  table.addColumn("Time");
  table.addColumn("Date");
}

void draw()
{ print(1);
  //variables called each time a new data entry is received
  int d = day();
  int m = month();
  int y = year();
  int h = hour();
  int min = minute();
  int s = second();
  //int s_prev=0;
  char d1 = 'a';

  if(mySerial.available() > 0)
  { //print(2);

    //set the value recieved as a String
    String value = mySerial.readString();
    //check to make sure there is a value
    if(value != null)
    {
      String[] parts = value.split("x"); //returns an array with the 2 parts

      //print(parts);
      //print('\n');
      for(int i=0;i<parts.length;i++)
      {

        String Part = parts[i];
        TableRow newRow = table.addRow();
        //place the new row and value under the "Data" column
        newRow.setString("Data", Part);
        //place the new row and time under the "Time" column
        newRow.setString("Time", str(h) + ":" + str(min) + ":" + str(s));
        //place the new row and date under the "Date" column
        newRow.setString("Date", str(s + 100));// + "/" + str(m) + "/" + str(y));
      }
    }
  }
print(4);}

void keyPressed()
{ print(5);
  //variables used for the filename timestamp
  int d = day();
  int m = month();
  int h = hour();
  int min = minute();
  int s = second();
  //variable as string under the data folder set as (mm-dd--hh-min-s.csv)
  filename = "data/" + str(m) + "-" + str(d) + "--" + str(h) + "-" + str(min) + "-" + str(s) + ".csv";
  //save as a table in csv format(data/table - data folder name table)
  saveTable(table, filename);
  exit();
}

This is my arduino code:

int val[2000];
void setup()
{
  Serial.begin(250000);

  //ADCSRA = 0;             // clear ADCSRA register
  //ADCSRB = 0;             // clear ADCSRB register
  ADCSRA &= ~(bit (ADPS0) | bit (ADPS1) | bit (ADPS2)); // clear prescaler bits
  //ADCSRA |= bit (ADPS0);                               //   2
  ADCSRA |= bit (ADPS1);                               //   4
  //ADCSRA |= bit (ADPS0) | bit (ADPS1);                 //   8
  //ADCSRA |= bit (ADPS2);                               //  16
  //ADCSRA |= bit (ADPS0) | bit (ADPS2);                 //  32
  //ADCSRA |= bit (ADPS1) | bit (ADPS2);                 //  64
  //ADCSRA |= bit (ADPS0) | bit (ADPS1) | bit (ADPS2);   // 128
  //pinMode(A0, INPUT);

}

void loop()
{
  for(int i=0; i<2000; i++) {
    val[i] = analogRead(A0);
  }
  for(int i=0;i<2000;i++){
    Serial.print(val[i]);
    Serial.print('x');
  }

}

You are doing 2000 samples really close together in rapid succession with no concept of time between them, then you are spending a considerable amount of time sending that data through serial.

That's not how you sample signals.

Instead, you need to set up some kind of time-based periodic sampling system, either through a timer interrupt or some other facility provided by the ADC (read the datasheet to see what interrupts the ADC can generate and what sample trigger sources there are) which runs completely asynchronously.  Then when (and only when) a sample set has been captured do you send that data through serial.

If your sampling takes longer than your sending through serial (unlikely) and you have the memory for it you can set up two buffers and "ping-pong" between them so you are sampling at the same time as sending.  Otherwise, all you will be able to do is capture a short window of data and then send it afterwards, so you get short bursts of samples.


Low-power detect rise and fall of input signal For a very low-power-project (where I want to keep the micro-controller asleep or powerless as much as possible), I need to detect the rising and the falling of an input-signal (which could power-on the controller and send a signal).

I tried sleeping and waking up the controller via an interrupt, but it would be even better to switch of the controller completely and just power up when there is a change in input signal (only a few times a day, with a signal length of several minutes).

Making the controller powerless (and processing all there is to be done in the setup before switching off again) is a better solution than the deep sleep solution, because of the low frequency of occurence of the input signal changes.

The output does not have to be exactly 30 seconds, it can be any other value. It could use a power latch.

I looked at monostable circuits but they only detect (generate a pulse) on rising.

Does anyone have a solution (which only costs a few uAmps) for this?

Thanks.

Addendum:

Voltage is 3.3V, current is "as low as possible" because this circuit should work as long as possible on a few cells. The input signal is generated by a mercury switch mounted on a bridge (which can be opened and closed)...

Instead of waking up from deep sleep (and being able to calculate the number of hours the circuit can last on an small battery) it is far better to power off "completely" and being able to calculate the number of activations from the bridge-movement (as long as the electronics I am looking for consume less than the deep sleep). Power consumption by the micro-controller+circuits is in deep sleep >10mA (too much for battery).

You can generate a pulse on any edge of a signal using some logic gates. For instance combining a rising edge detector with a falling edge detector and adding a time delay would probably achieve what you want:

simulate this circuit – Schematic created using CircuitLab

Simulate it here.

The length of time the pulse is on for is (roughly) defined by the time constant of R1 and C1.  That's T=RC, so in this instance 100 x 0.0000001 =  10uS.

for a time of (say) 30 seconds, you will want to massively increase those values. For example, 470uF and 80K would give you around 32 seconds.

Power consumption? Well, that's all dependent on the logic gates and how you build the circuit.  74HC chips are pretty efficient now (far better than the old 74LS ones), but you will want to reduce it down to as few chips and gates as possible. That means converting the circuit to just one gate type (for example NAND) and reducing redundancy in the circuit to minimise power consumption.


Bluetooth Master and Slave to track device's locations I'm trying to create an app for my science fair that uses bluetooth to track people in a determined place.
I was thinking about one Arduino system to receive all the information and transmit through a network and some Arduino slaves to duplicate the signal and cover the hole place.

Resuming...

I'll have:

Arduino slaves placed all over the place to track people
One Arduino connected to the network to receive all the information from the slaves and pass it through the network.
Some kind of web app inside the main Arduino with an API to manage the data and make it friendly for third-party apps

I was wondering of what kind of equipment should I buy to make this happen. Thanks!

Each cellphone with it's bluetooth enabled will work as a person (sending signal) - my Arduino slaves will receive the signal (find bluetooth around it) and send the device name and signal strength to the arduino master - The arduino master (connected to the network) will interpenetrate the responses and send the results to the built-in web server - Apps will make requests to the web app to get this data and show in a plant where're these people.

Basically it will work like these bluetooth stickers that you can plug in to your keys, phone e etc... and with the app you can search for them in your house via bluetooth from your cellphone.

Here's a better explanation:
Link

Bluetooth generally support only one to one connection. Atmost 6 bluetooth can be connected to single module in latest bluetooth version(the basic model probably used by you connects only 1 device). Hence it is not a good idea to use bluetooth. Also if you need a web based platform you should switch to some more powerful platform like raspberry pi, beagle bone etc.


Testing 433MHz Transmitter Folks,
There is a document named "Complete Guide for RF 433MHz Transmitter.pdf" available in the GitHub.
There is a a connection diagram showing the Data pin of the Transmitter connected to the pin 12 of the Arduino Uno.
The Transmitter sketch given in it is as follows:
#include <RH_ASK.h>
#include <SPI.h> // Not actually used but needed to compile

RH_ASK driver;

void setup()
{
 Serial.begin(9600); // Debugging only
 if (!driver.init())
 Serial.println("init failed");
}

void loop()
{
 const char *msg = "Hello World!";
 driver.send((uint8_t *)msg, strlen(msg));
 driver.waitPacketSent();
 delay(1000);
}

There is no mention of Pin 12 as part of the sketch. I am not sure how the Arduino knows the Transmitter Data input is connected to the Pin 12? Can someone please help?
Ranjith

In RH_ASK.h is:
RH_ASK(uint16_t speed = 2000, uint8_t rxPin = 11, uint8_t txPin = 12, uint8_t pttPin = 10, bool pttInverted = false);

So the argument has a default value specified here.  If you don't specify it, it assumes that default.


What is the overhead time of using Serial library compared to coding it up in AVR C (not using Arduino code)? I am using an Arduino UNO to drive a UART throughput test and to also test the latency of the slave microcontroller.

The setup is as follows:

Arduino|---UART--------------------------|MCU2

Arduino|---FLOW_CONTROL_PIN---|MCU2

I am sending data to the MCU2 over the UART with a specified delay between writes, and in MCU2 I have a certain buffer threshold where I set an overflow pin indicator back to the Arduino (using INT0), where when the interrupt is triggered, I stop sending data (hardware based flow control).

At this point I log the amount of bytes sent and compare that to the buffer threshold level.  If the bytes sent are equal to the threshold point, I know the latency of the path (threshold-->toggle flow pin-->Arduino interrupt and stop transmit) is ok (if not, we are having latency issues and probably need to do a software based flow control). I then do the whole process again, with a shorter delay.  I then can find the delay point that will result in the fastest continuous transfer rate (this is testing throughput as well as latency of the slave MCU).

A problem can arise if the Arduino api is providing more latency than the path under test.  I believe this is most likely the case, but wanted to see if there has been any concrete numbers on the overhead of Arduino, particularly in regard to its Serial api.  I used Arduino to get something running quickly, but if it doesn't allow me to actually test the system, need to go to using all AVR C or use another MCU for the transmit side.

There's no reason to doubt the Arduino hardware. We need to put some figures on what you are experiencing, such as the baud rate and buffer sizes.

I would expect with this sort of hardware flow-control that you would potentially send a byte or so more than expected, because it takes a finite time to react to the flow-control signal. This is to be expected, particularly as the hardware has a buffer, so it can be starting to send a byte at the moment you get the signal to stop sending.

I expect you would have a leeway (say of 10 bytes) where you expect the sender to stop sending within that time.

  A problem can arise if the Arduino API is providing more latency than the path under test

I'm not sure what you mean by this. However the HardwareSerial class has a 64-byte buffer (if you are using a Uno) which means you potentially have put 64 bytes into it, before noticing that the sender wants you to stop sending.

This is probably what you are experiencing. See HardwareSerial.cpp:

// Define constants and variables for buffering incoming serial data.  We're
// using a ring buffer (I think), in which head is the index of the location
// to which to write the next incoming character and tail is the index of the
// location from which to read.
#if (RAMEND < 1000)
  #define SERIAL_BUFFER_SIZE 16
#else
  #define SERIAL_BUFFER_SIZE 64
#endif

For this test you might want to edit that file and reduce that number, substantially.

Alternatively, use SoftwareSerial. I don't think that buffers writes (as it doesn't have hardware to do them in the background) so that would reduce the latency to a single byte.

  I believe this is most likely the case, but wanted to see if there has been any concrete numbers on the overhead of Arduino, particularly in regard to its Serial API.

It's not an overhead, it's a design issue. If you do what I suggested it should work fine.

  What I mean by Arduino API overhead is the fact that the actual hardware interface is substantially abstracted away from the register level implementation ...

Well, not really. When you write a byte it puts it into a circular buffer, as you would expect. When the hardware is free to output another byte (generally called by an interrupt) it outputs it. What else could it do?

However you are absolutely free to address the hardware registers yourself and not use HardwareSerial.

To keep things simple though, what you really need to do here is not buffer because that makes reacting to the flow-control flag somewhat slow. And here is how to do it:

Serial.write ('a');  // or whatever
Serial.flush ();  // wait until everything is sent

Now you have thrown away the buffering, and you can just send at the rate that the hardware can (probably slightly less).


Using both a stepper motor and a DC motor with Arduino motor shield R3 We are trying to reprogram a remote control car with an Arduino Uno. This car runs the power with a DC motor, and it controls steering using a stepper motor.

We have the Motor Shield R3 attached to the Arduino, but it has just now occurred to us that we can't support both motors with the motor shield (as the motor shield only allows for two DC motors or one stepper motor). Is there a way to somehow work around this? Or is it possible that we would need to replace the stepper motor with DC?

You are right: Motor Shield R3 can drive two DC motors or one step motor. So, there are 2 (maybe  3) solutions:
1. Have another shield - now you can drive 2 step motors, or one DC motor(using 'half' of shield, and one step motor using another whole shield.
2. Replace your step motors with DC motor. This option can be more complicated, as no precise position control will be possible when you try to use DC motor for steering. (DC motor are hard to select and hold position, when stepper motors are quite easy to 'go to certain position' AND 'hold'). There is also good mechanical skill needed to remove/place it precisely.

optional option 3. Instead of Motor Shield R3 you can try to use cheap Easy Driver to drive your step motor.


Why do i get additional characters when reading a file through a buffer if buffer size > 15? This is a follow up question to How to speed up writing a file to a WifiClient?

I modified the old code to read from one Stream and write to another which looked like this and worked fine albite being a bit slow

while (file.available() > 0)
{
    client.print((char)file.read());
}
client.flush();

to use a buffer, like so

char buffer[300];
size_t bufferSize = sizeof(buffer);

// ...

while (file.available() > 0)
{
    memset(buffer, 0, bufferSize);
    file.read(buffer, bufferSize);

    client.print(buffer);
}
client.flush();

Now, if the buffer size is > 15 (in the above case, it's 300), two additional characters Øb are introduced after the buffer size amount of characters. If the buffer size is <= 15, this does not happen.

If the file to be read contains abcdefg repeated several times, I get the following result for a buffer size of 32:

|-------- 32 characters -------|Øb|-------- 32 characters -------|Øb|-----
abcdefgabcdefgabcdefgabcdefgabcdØbefgabcdefgabcdefgabcdefgabcdefgaØbbcdefg

What's causing those additional characters to appear?

The above output is produced in the browser If I do not specify a charset. if I do, I get � instead of Øb.

Try recording the actual number of bytes read and only write that number of bytes:

size_t nr = file.read(buffer, bufferSize);
client.write(buffer, nr);


How can I get analog-in reading from Digital-PWM-out on the same board? I have a wire going from PWM4 to A0 but I don't dare turn on my Arduino Mega in case this is incorrect.

PWM4 will eventually go to an analog device but I want to make sure the read value is what I expect it to be. Am I okay to proceed with my current setup or do I need to throw in a resistor / conversion?

You are fine by doing that, but you won't get what you expect.

A PWM signal isn't an analog value. It's a series of pulses, the duration of those pulses is set by the (not accurately called) analogWrite. So sometimes the value is 5V and sometimes it's 0V. You need to get the average value by adding e.g. an RC-filter.

Another option is to add a proper DAC (digital to analog converter) chip to your circuit.


How to call C functions from Arduino sketch? I would like to know if there is a way to call functions that are contained within C files using an Arduino sketch?

My C file declares and defines a function. To save putting the messy function definition into my Arduino sketch, I'd like to call the function straight from the sketch.

Is there a standard way to do this using Arduino and C?
Here is the sketch:

#include "crc16.h";

void setup(){

}

void loop(){

  CalculateCRC16("<09M", 4);

}

and this is the trimmed down C file:

#include <stdio.h>
#include <stdint.h>

uint16_t crctable[256] =
{
    0x0000, 0x1189,.....

uint16_t // Returns Calculated CRC value
CalculateCRC16( // Call example CalculateCRC16("<09M", 4);
    const void *c_ptr, // Pointer to byte array to perform CRC on
    size_t len)        // Number of bytes to CRC
{

    uint16_t crc = 0xFFFF // Seed for CRC calculation
    const uint8_t *c = c_ptr;

    while (len--)
        crc = (crc << 8) ^ crctable[((crc >> 8) ^ *c++)];

    return crc;
}

You can extern "C" #include like the following:

extern "C"{
#include "crc16.h"
};

void setup(){
}

void loop(){
  CalculateCRC16("<09M", 4);
}

And the crc16.h file could be (some minor fixes, the #pragma once, a cast):

#pragma once

#include <stdio.h>
#include <stdint.h>

uint16_t crctable[2] ={ 0x0000, 0x1189};

uint16_t CalculateCRC16( // Call example CalculateCRC16("<09M", 4);
    const void *c_ptr, // Pointer to byte array to perform CRC on
    size_t len)        // Number of bytes to CRC
{
    uint16_t crc = 0xFFFF; // Seed for CRC calculation
    const uint8_t *c = (const uint8_t *)c_ptr;

    while (len--)
        crc = (crc << 8) ^ crctable[((crc >> 8) ^ *c++)];

    return crc;
}


Passing the input from one pin to another as output without polling? I am trying to pass the input from one pin to another pin as output. Effectively I want to create a blind passthrough. The end goal is to connect two Arduinos and a series of test points together like the diagram below. I want Arduino B to shuffle which test points are connected to which pins on Arduino A on startup.

+-----------+       +-----------+     +-------------+
|           |       |           |     |             |
| Arduino A <-------> Arduino B <-----> Test Points |
|           |       |           |     |             |
+-----------+       +-----------+     +-------------+

I figure one way to do this is to poll the input pins in the loop() and then change the output pins accordingly but I would prefer if the voltage changes just passed right through without it affecting timing.

Update:
For some clarification:

All signaling is digital
I'm looking to "route" around 10-12 test points to Arduino A ideally but 6 at a minimum

You could use an analog multiplexer such as the 74HC4051 (8 channels) or the 74HC4067 (16 channels) like this:

Arduino B could alter the multiplex selector (A/B/C) pins to route the signal from the test points to a specific pin on Arduino A. If you are wanting to see the result of the signal on a different pin then a second multiplexer would be required (ie. one to send data to a pin, the second to see the result on a different pin).

I have a post about the 74HC4051 multiplexer / demultiplexer which gives more details about using it.

When I tested it I found only about a 5 ns delay in timing:

Ignacio's answer about a crossbar switch sounds like a more elaborate form of multiplexer. Personally I haven't used one of them.


Arduino loading from file Hello I have a programme that loads a piece of text from a file. In this case it loads "drawrect(4,10,20,20);" from the txt file and stores it in a string. I then use substrings to change the string into just "4,10,20,20" which is good but I need to simplify it down even more to four strings each with one of those 4 numbers in it.

Currently I use:

void drawRectMethod(String s){
  String var1,var2,var3,var4;
  s = s.substring(s.indexOf('(') + 1);
  s = s.substring(0, s.lastIndexOf(')'));
  Serial.println(s);
}

to simplify the string down to "4,10,20,20" but this wont work to store each number in a separate string. How can I can I store each variable in a separate string. The numbers will be stored in var1 - var4.

Need some more help? As I previously wrote that snippet I might as well continue until you understand how to use indexOf() and substring().

  String s = "draw(10,20,30,40)";

  // Parse the argument list
  s = s.substring(s.indexOf('(') + 1);
  s = s.substring(0, s.lastIndexOf(')'));

  // Parse comma separated arguments
  String arg[4];
  for (int i = 0; i < 3; i++) {
    int ix = s.indexOf(',');
    arg[i] = s.substring(0, ix);
    s = s.substring(ix + 1);
    Serial.println(arg[i]);
  }
  arg[3] = s;
  Serial.println(arg[3]);

There is absolutely no error handling in this. You will have to add that. You can also improve the parse of the right parenthesis. That could be added last instead.

Later in the game we will come to why using String is a bad idea and why a character buffer and the standard library functions such as strtok() is a much better solution strategy both performance and memory footprint and especially heap.

  char* s = (char*) "draw(10,20,30,40)";
  s = strtok(s, "(),");
  Serial.println(s);
  while ((s = strtok(NULL, "(),")) != NULL)
    Serial.println(s);

Maybe the simplest solution is to use sscanf(). That will also do the conversion from text to binary.

  const char* s = "draw(10,20,30,40)";
  int x, y, w, h;
  int n = sscanf(s, "draw(%d,%d,%d,%d)", &x, &y, &w, &h);
  Serial.print(F("n="));
  Serial.println(n);
  Serial.print(F("x="));
  Serial.println(x);
  Serial.print(F("y="));
  Serial.println(y);
  Serial.print(F("w="));
  Serial.println(w);
  Serial.print(F("h="));
  Serial.println(h);

Cheers!


How to program a CLK signal and its inverse with Arduino/AVR Is it possible to simultaneously output a clock signal and it's inverse using the timer register(s)?

I'm using the following code in arduino to output a 1MHz signal on OC1A:

//Use Timer/Counter1 to generate a 1MHz square wave on Arduino pin 9.
//J.Christensen 27Apr2012

void setup(void)
{
    DDRB = _BV(DDB1);                  //set OC1A/PB1 as output (Arduino pin D9, DIP pin 15)
    TCCR1A = _BV(COM1A0);              //toggle OC1A on compare match
    OCR1A = 7;                         //top value for counter
    TCCR1B = _BV(WGM12) | _BV(CS10);   //CTC mode, prescaler clock/1
}

void loop(void)
{
}

How about this?

void setup()
  {
  // Defining PB1 and PB2 as outputs by setting PORTB1 and PORTB2
  // Setting DDB1 and DDB2
  DDRB |= bit (DDB1) | bit (DDB2);

  // stop timer 1
  TCCR1A = 0;
  TCCR1B = 0;

  TCCR1A = bit (COM1B0) | bit (COM1B1)  // Set OC1B on Compare Match, clear
                                        // OC1B at BOTTOM (inverting mode)
         | bit (COM1A1)                 // Clear OC1A on Compare Match, set
                                        // OC1A at BOTTOM (non-inverting mode)
         | bit (WGM11);                 // Fast PWM, top at ICR1
  TCCR1B = bit (WGM12)  | bit (WGM13)   //       ditto
         | bit (CS11);                  // Start timer, prescaler of 8

  // Initialize OCR1A = 300 (pulse_width = 150us), OCR1B, and ICR1
  ICR1 = 0xFFFF;
  OCR1B = 299;
  OCR1A = ICR1 - OCR1B;

  }  // end of setup

void loop()
  {
  }

Results on a Uno:

Output on Uno pins 9 and 10.

Change the prescalers and counters to your desired frequency.

The screenshot doesn't show one signal exactly the inverse of the other. The pattern is inverted. If you had a 50% duty cycle, it would be an exact inverse.

  It looks good except they overlap (slightly) by 50ns. If I set them to 16 and 8, respectively, they don't overlap but they are slightly asymmetrical

OK, make OCR1A and OCR1B both 7:

  ICR1 = 15;
  OCR1B = 7;
  OCR1A = 7;

Why 7? And why 15?

The counts are zero-relative. So by counting to 15 on a 16 MHz processor we are actually getting 1/16th of the clock, namely 1 MHz. And half of that is 8 (which, zero-relative, is 7). So we are really doing:

Period: 16 ticks of the 16 MHz clock
Duty cycle: 8 ticks of the 16 MHz clock

Now, one cycle:

They change over at the same instant - pulse width exactly 500 ns.

And they change back at the same moment - pulse width also 500 ns.


Load website from SD card I combined two different codes together, a captive portal and a SD card web server. I encountered a problem which the website in the SD card doesn't load when I connect to the AP (captive portal page). Here's the code..

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include "./DNSServer.h"
#include <SPI.h>
#include <SD.h>

const byte        DNS_PORT = 53;          // Capture DNS requests on port 53
IPAddress         apIP(10, 10, 10, 1);    // Private network for server
DNSServer         dnsServer;              // Create the DNS object
ESP8266WebServer server(80);
String responseHTML = ""
                      "<title>Captive Portal Test</title>"
                      "
TEST
";

static bool hasSD = false;
File uploadFile;

void returnOK() {
  server.send(200, "text/plain", "");
}

void returnFail(String msg) {
  server.send(500, "text/plain", msg + "\r\n");
}

bool loadFromSdCard(String path) {
  String dataType = "text/plain";
  if (path.endsWith("/")) path += "index.htm";
  if (path.endsWith(".src")) path = path.substring(0, path.lastIndexOf("."));
  else if (path.endsWith(".htm")) dataType = "text/html";
  else if (path.endsWith(".css")) dataType = "text/css";
  else if (path.endsWith(".js")) dataType = "application/javascript";
  else if (path.endsWith(".png")) dataType = "image/png";
  else if (path.endsWith(".gif")) dataType = "image/gif";
  else if (path.endsWith(".jpg")) dataType = "image/jpeg";
  else if (path.endsWith(".ico")) dataType = "image/x-icon";
  else if (path.endsWith(".xml")) dataType = "text/xml";
  else if (path.endsWith(".pdf")) dataType = "application/pdf";
  else if (path.endsWith(".zip")) dataType = "application/zip";

  File dataFile = SD.open(path.c_str());
  if (dataFile.isDirectory()) {
    path += "/index.htm";
    dataType = "text/html";
    dataFile = SD.open(path.c_str());
  }

  if (!dataFile)
    return false;

  if (server.hasArg("download")) dataType = "application/octet-stream";

  if (server.streamFile(dataFile, dataType) != dataFile.size()) {
  }

  dataFile.close();
  return true;
}

void handleNotFound() {
  if (hasSD && loadFromSdCard(server.uri())) return;
  String message = "SDCARD Not Detected\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i = 0; i < server.args(); i++) {
    message += " NAME:" + server.argName(i) + "\n VALUE:" + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
}

void setup(void) {
  WiFi.mode(WIFI_AP);
  WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
  WiFi.softAP("TEST AP");
  dnsServer.start(DNS_PORT, "*", apIP);
  //PROBLEM HERE/
  server.onNotFound([]() {
  server.send(200, "text/html", responseHTML);
  });

  server.begin();

  if (SD.begin(SS)) {
    hasSD = true;
  }
}

void loop(void) {
  dnsServer.processNextRequest();
  server.handleClient();
}

This code replies the responseHTML as a Captive portal page which immediately pop-ups when I connect to the AP:

server.onNotFound([]() {
      server.send(200, "text/html", responseHTML);
      });

The void handleNotFound() handles the page/file request from the browser but if I use it on

server.onNotFound(handleNotFound);

The captive portal won't show but if I type the server address 10.10.10.1, the page will appear. What seems to be the problem?

Remove hasSD && from void handleNotFound() function.
It worked for me.


TEENSY 3.2 RS-232 throughput I have an application where I need 4 serial ports - 3 will be sending and receiving.  The packet size will be up to 255 bytes on these 3 "main" ports.  The 4th port will be receive only, and its packet size will be 6 bytes. There is no flow control. The data rate on all ports is 115,200 baud. The 3 main ports will send or receive data packets approximately once per second. Most data will be half-duplex, although occasionally it will be necessary to send and receive simultaneously from a port . The 4th port (the one that handles 6 bytes), will get packets at an approx 50 packets/second rate.

The TEENSY will have to calculate CRCs on all ports, and will have to do a small amount of data manipulation as well.

I was planning to use the hardware serial ports for the 3 main ports, and software serial for the port that has to deal with only 6 bytes.  It is important that the 3 main ports be able to not miss any incoming data.  The 4th port is less important and can "miss" a packet now and then with no ill effects.

Will a TEENSY 3.2 running 90MHz be able to keep up?

Once per second? I don't see any problem, I will try to calculate:

3 ports: send + receive 255 bytes, let's say 270 bytes (with start/stop bits, probably way too much) per message:

3 * 2 (send + receive) * 270 = 1620 bytes
4th port: 50 * 6 bytes = 300 bytes

Total: 1920 bps

The serials can easily keep up with this, so that is not a problem.

90 MHz is 90 million instructions per second. As you can see, handling 1620 bytes is nothing ... it could do many more, a factor of multiple thousands more.

Unless of course you want to do heavily calculations for the received/sent data.


How to read OC0A when in CTC (toggle) mode? I have this code, which puts the Arduino into CTC mode with interrupts, and outputs a square wave on PD6 (OC0A):
void setup_timer(double p_ms, double duty){
  DDRD |= (1 << 6);  // set pin 3 as output
  TCCR0A = _BV(COM0A0); // toggle OC0A on Compare Match
  TCCR0B = _BV(WGM01); // set CTC mode WGM0[2,1,0] = 0b010
  TIMSK0 |= _BV(OCIE0A); // Enable CTC interrupt
  OCR0A = 128;  // set on and off time
  TCCR0B |= ( (0 << CS02) | (0 << CS01) | ( 1 << CS00)); // CS02:0 - No prescaling
  sei();
}

In the ISR (which is not shown) I want to be able to see whether OC0A (i.e. PD6) is HIGH or LOW.
I assumed that I could do a digitalRead(), but this post, Re: How to read the state of an output pin ? says:

Looking at the code the digitalRead() function just does a read of the appropriate bit in the appropriate PINx register without modifying anything, so it should work.
One catch, if it's a PWM pin the PWM will be stopped.

So, will the toggling of OCR0A be stopped?
This answer to How can I digitalRead a pin that is in pinMode OUTPUT? suggests reading PORTD directly, with
bitRead(PORTD,6);

However, will that work for PWM output or will PWM also be stopped by reading PORTD?

Addendum
I plan to use this code either as (primarily) a stand alone AVR µController (48/88/168/328 IC), but maybe in a Nano/Uno (if it will work) for testing purposes. I understand that using Timer0 will affect the operation of millis(), delay() etc., but the rest of the code will not rely on any of those functions... so I presume (maybe incorrectly) that the code will work as expected. Is that correct?
In addition, I don't intend on using a setup() & loop() program structure but rather main(). Just out of interest, would loop() work (i.e. is it reliant on Timer0)? I don't believe that it is.

If you look into the Arduino Core, you'll find this code for the digital read:

int digitalRead(uint8_t pin)
{
    uint8_t timer = digitalPinToTimer(pin);
    uint8_t bit = digitalPinToBitMask(pin);
    uint8_t port = digitalPinToPort(pin);

    if (port == NOT_A_PIN) return LOW;

    // If the pin that support PWM output, we need to turn it off
    // before getting a digital reading.
    if (timer != NOT_ON_TIMER) turnOffPWM(timer);

    if (*portInputRegister(port) & bit) return HIGH;
    return LOW;
}

That means, disabling PWM is just weird feature in digitalRead.

For reading bitRead(PORTB,3); I'm not so sure if you'll get output value of OC0A, it might be different signal line internally. However you'll get logical level on the port pin by reading bitRead(PINB,3);.


exit status 1 error compiling for board arduino/Genuino Uno when tone code is used I am just trying to use an ultrasonic sensor with a buzzer but the buzzer doesn't respond to my code. I mean it doesn't make any sound. I tested it to check if by sending 5 volts to it, it will make a sound.. and it did... but using this code below... for some reason, it doesn't make any sound....

#include <NewPing.h>
#define TRIGGER_PIN 11
#define  ECHO_PIN 12
#define buzzer 13

NewPing sonar1 (TRIGGER_PIN, ECHO_PIN);

long inches1;
int sound = 250;

void setup (){

  Serial.begin (9600);

  pinMode (TRIGGER_PIN, OUTPUT);
  pinMode (ECHO_PIN, INPUT);
  pinMode (buzzer, OUTPUT);

}

void loop () {

  inches1 = sonar1.ping_in();
   if (inches1 <= 5 ){
 //   sound = 250;
    tone(buzzer, 1000); // Send 1KHz sound signal...
    delay(1000);        // ...for 1 sec
    noTone(buzzer);     // Stop sound...
    delay(1000);
    Serial.print (inches1);
    Serial.print ('\n');
   }
  delay (200);
}

If you have a look at the complete error message you will see that there is a collision between the libraries NewPing and Tone.

Arduino: 1.8.9 (Windows Store 1.8.21.0) (Windows 10), Board: "Arduino/Genuino Uno"

Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':

(.text+0x0): multiple definition of `__vector_7'

libraries\NewPing\NewPing.cpp.o (symbol from plugin):(.text+0x0): first defined here

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Arduino/Genuino Uno.


Transmitting sketches to Yun with Autobahn - a byte at a time? I am using this tutorial to connect an Arduino Yun with a browser using Autobahn.

In the python file in the above repo, there is this code:

def controlLed(self, turnOn):
    if turnOn:
        payload = b'1'
    else:
        payload = b'0'
    self.transport.write(payload)

Here's the thing - I need to send whole sketches to my Yun, not just '1' or '0'. I tried sending more to the payload (like payload = b'this is part or all of a sketch') but that doesn't work. I experimented with some other data types but at the moment these are shots in the dark.

How can I send some proper data (like 100 lines of Arduino sketch) with this mechanism? The end goal is that my existing sketch receives the new sketch commands via serial and runs them.

if (port->available()) {
  int commands = port->read();
  // Run commands here
}

I would be hugely appreciative of any help. Thank you!

Partial answer: to send more information than just a single byte, it is possible to run:

# python
payload = "Here is a longer string"

# arduino
String commands = port->readString();           // Reads the whole thing
String commands = port->readStringUntil('\n');  // Reads until the given separator


ard-reset-arduino resetting Leonardo/Micro via USB works on OSX, fails on Ubuntu I'm trying to program a Leonardo (actually a Micro ATmega32U4) via the command line using USB.  Schematically, I'm doing ard-reset-arduino followed by a sleep 1 and an avrdude command.

This works reliably on my Mac (OSX 10.12.1, avrdude v6.3), but bombs out on Ubuntu (Ubuntu 5.2.1-22ubuntu2, avrdude v6.1) with the message:

.avrdude: butterfly_recv(): programmer is not responding

Update: I believe this is actually due to a failure to get the atmega32u4 into the bootloader.  See update at the bottom of this post...

Has anyone seen this?  Any suggestions for debugging strategies or things to try?

Details on the Mac:

Here is the command line with results under OS X:

$ ./ard-reset-arduino --verbose --caterina /dev/cu.usbmodem1411 && sleep 1 && /Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -V -D -p atmega32u4 -C /Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -c avr109 -b 9600 -P /dev/cu.usbmodem1411 -U flash:w:./leds_test.ino.leonardo.hex:i
Forcing reset using 1200bps open/close on port /dev/cu.usbmodem1411
/dev/cu.usbmodem1411 has come back after reset

Connecting to programmer: .
Found programmer: Id = "CATERIN"; type = S
    Software Version = 1.0; No Hardware Version given.
Programmer supports auto addr increment.
Programmer supports buffered memory access with buffersize=128 bytes.
Programmer supports the following devices:
    Device code: 0x44

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e9587 (probably m32u4)
avrdude: reading input file "./leds_test.ino.leonardo.hex"
avrdude: writing flash (9146 bytes):

Writing | ################################################## | 100% 0.70s

avrdude: 9146 bytes of flash written
avrdude: safemode: Fuses OK (E:CB, H:D8, L:FF)
avrdude done.  Thank you.

Details on Ubuntu:

Here is the command line with results under Ubuntu.  Except for the pathnames, all of the options are the same as under OSX:

$ /boot/ard-reset-arduino --verbose --caterina /dev/ttyACM0 && sleep 1 && /usr/share/arduino/hardware/tools/avr/../avrdude -V -D -p atmega32u4 -C /usr/share/arduino/hardware/tools/avr/../avrdude.conf -c avr109 -b 9600 -P /dev/ttyACM0 -U flash:w:/boot/leds_test.ino.leonardo.hex:i
Forcing reset using 1200bps open/close on port /dev/ttyACM0
Waiting for /dev/ttyACM0 to come back
Waiting for /dev/ttyACM0 to come back
Waiting for /dev/ttyACM0 to come back
Waiting for /dev/ttyACM0 to come back
Waiting for /dev/ttyACM0 to come back
Waiting for /dev/ttyACM0 to come back
Waiting for /dev/ttyACM0 to come back
Waiting for /dev/ttyACM0 to come back
/dev/ttyACM0 has come back after reset

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

Postscript

Just to make sure I hadn't borked the bootloader somehow, I moved the Leonardo/Micro back to the OSX and re-ran the reset / programming sequence under OSX.  It worked without error, so I conclude that the resident bootloader is intact.

Update

I believe the real problem is that under Ubuntu, ard-reset-arduino fails to put the Leonardo into the bootloader.

Here's why I believe this is the problem: the resident sketch makes the onboard LEDs blink.  On the Mac, running ard-reset-arduino makes the blinking stop for about 8 seconds.  On Ubuntu, the LEDs continue to blink without interruption after the ard-reset-arduino command returns.

Update 2

Here's an even simpler Python program that resets the Leonardo under OSX but not under Ubuntu.

#! /usr/bin/python
import sys
import serial

ser = serial.Serial(sys.argv[1], 1200)
ser.close()

I'm somewhat embarrassed as to the source of the problem.  It wasn't an OSX vs Ubuntu issue.

Rather, on the Ubuntu system, there was an another application that was holding the USB port open, so attempts to reset the Leonardo were failing.

Rather than delete this post out of shame, I'm leaving it here in case someone else stumbles across the same problem.


What does the 'arduino' avrdude programmer do? The command line that my toolchain (CLion + PlatformIO) uses to program my Arduino (Uno) includes includes

avrdude ... -c arduino ...

but the documentation for this programmer simply reads

  -c programmer-id
           ...
          arduino           Arduino
           ...

What does the arduino programmer do. Does it just correspond to using the bootloader?

Yes, the -c option specifies the methods of interacting with the device's loader.

The source code of the arduino programmer is http://svn.savannah.nongnu.org/viewvc/trunk/avrdude/arduino.c?root=avrdude&view=markup

Specifically, '-c arduino' chooses the client side code tailored to the bootloader in the Arduino Uno.  Looking at the code in the above link, it tweaks the DTR and RTS lines to get the Ardunino into an stk500 compatible mode, and then invokes the stk500 protocol.


Reading SNMP V2 OID from ESP8266/ESP32 i need to read from my ESP32/ESP8266 some SNMP V2 OID values from my home printer: it exists a library/method that can do that?
I've seen some SNMP agents, but they works only with the devie as server and not as SNMP client.
Any thoughts?

Not sure if you found it, but there I created an SNMP Manager: https://github.com/shortbloke/Arduino_SNMP_Manager
There is also an SNMP Agent: https://github.com/0neblock/Arduino_SNMP
I know this is a bit later than when you requested this info. But posting here in case it's still helpful to you or others that stumble over this question.


Arduino with two (or more) push buttons I am trying modify this setup for two push buttons https://www.arduino.cc/en/Tutorial/Button.

The code seems rather trivial

int yellowButtonPin = 2;
int blueButtonPin = 4;

int yellowButtonState = 0;
int blueButtonState = 0;

void setup(){
  Serial.begin(9600);
  pinMode(yellowButtonPin,INPUT);
  pinMode(blueButtonPin,INPUT);
}

void loop(){
  yellowButtonState = digitalRead(yellowButtonPin);
  blueButtonState = digitalRead(blueButtonPin);
  if (yellowButtonState == HIGH && blueButtonState == HIGH){
    Serial.write(3);
  }
  else if (yellowButtonState == HIGH && blueButtonState == LOW){
    Serial.write(2);
  }
   else if (yellowButtonState == LOW && blueButtonState == HIGH){
    Serial.write(1);
  }
  else {
    Serial.write(0);
  }
}

My problem is that there are several ground pins on the Arduino, but only one 5V pin, so I can't just simple double the circuits. Connecting the two circuits to different grounds but the same 5V didn't work out, although it seemed to be a good idea. How should I do this properly? To be honest, I actually would want to have three buttons, but I guess going from two to three will be trivial after going from one to two.

Learn about:

Built-in pullup resistors in Arduino
Debouncing

and checks this code: https://blog.adafruit.com/2009/10/20/example-code-for-multi-button-checker-with-debouncing/