text:
Unexpected behavior of sprintf with i32/u32
I'm trying to build a string of characters from several elements given by the TinyGPS++ library with the use of sprintf().
This is my code making the string and printing it in the serial monitor.
char posmsg[100], lat[14+1], lon[14+1];

void sendString(){
  //- convert lat/lon
  dtostrf(gps.location.lat(), 10,6, lat);
  dtostrf(gps.location.lng(), 10,6, lon);

  //- sprintf the string
  sprintf(posmsg, "$%4d-%02d-%02d %02d:%02d:%02d,%s,%s,%i,%i,%i,%i,%i$",
          gps.date.year(),gps.date.month(),gps.date.day(),
          gps.time.hour(), gps.time.minute(), gps.time.second(),
          lat, lon,
          gps.speed.value(), gps.course.value(), gps.altitude.value(),
          gps.satellites.value(), gps.hdop.value()
        );

  Serial.println("--------------------");
  Serial.println(posmsg);
  Serial.println("--------------------");

  Serial.print("Speed:");
  Serial.println(gps.speed.value());
  Serial.print("Course:");Serial.println(gps.course.value());
  Serial.print("Height:");Serial.println(gps.altitude.value());
  Serial.print("Sats:");Serial.println(gps.satellites.value());
  Serial.print("HDOP:");Serial.println(gps.hdop.value());
  Serial.println("--------------------");
}

This is the result and what I expect... (spaces added for readability)
 Result:
 --------------------
 $2014-06-24 15:17:11,  51.xxxxxx,   5.xxxxxx, 2, 0, 4964, 0, 3660$
 --------------------
 Speed:2
 Course:4964
 Height:3660
 Sats:8
 HDOP:110
 --------------------

 Expected:
 --------------------
 $2014-06-24 15:17:11,  51.xxxxxx,   5.xxxxxx, 2, 4964, 3660, 8, 110$
 --------------------

So in the end of the string the numbers get displaced...
According to the documentation the type of the variables are all integers or unsigned integers, but the sprintf messes things up.
 gps.speed.value(); // Raw speed in 100ths of a knot (i32)
 gps.course.value(); // Raw course in 100ths of a degree (i32)
 gps.altitude.value(); // Raw altitude in centimeters (i32)
 gps.satellites.value(); // Number of satellites in use (u32)
 gps.hdop.value(); // Horizontal Dim. of Precision (100ths-i32)

What am I doing wrong?

Ints and unsigned ints are 16 bits on AVR ATmegas.
So while the argument passed is a 32-bit value, sprintf() is expecting a 16 bit value.  The stack is packed with twice as much data as needed.
From the "2,0,4964" bit, it looks like it taking part of the previous/next parameter during processing, which makes me think this even more.
You need to use long types, e.g.: %ld or %li and %lu


text:
Check contents of buffer after serial read
I would like to test the contents of data received over a serial connection. In my loop() I store the data in bffr; and afterwards I would like to test to see if there are some predefined words in it.
#define BFFSZ 90
char bffr[BFFSZ];
char bffridx;

void loop()
{
   readline();

   //- Test the bffr
       if(strstr(bffr, "CLOSED")){ //- WORKS
          Serial.println("> conn. closed");
          digitalWrite(A1, HIGH);
       }else if(strstr(bffr, "RING")){ //- WORKS
          Serial.println("> Someone is ringing");
          digitalWrite(A2, HIGH);
       }else if(strstr(bffr, "0,7,j,BLINK")){ //- Doesn't work
          Serial.println("> Blink");
          digitalWrite(A2, HIGH);
          delay(300);
          digitalWrite(A2, LOW);
       }
}

void readline()
{
   memset(bffr,0,sizeof(bffr));
   char c;
   int i =0;
   bffridx = 0; // start at beginning

   long previousMillis = millis();
   while (1) {
     unsigned long currentMillis = millis();
     if(currentMillis - previousMillis > 20000) {
       Serial.println("TIMEOUT");
       return;
     }
     delay(2);

     c=gsm.SimpleRead2();
     //- debug only, to see if there is something received.
     Serial.write(c);

     if (c == -1)
       continue;
     if (c == '\n')
       continue;
     if ((bffridx == BFFSZ-1) || (c == '\r')) {
       bffr[bffridx] = 0;
       return;
     }

     bffr[bffridx++]= c;
     delay(2);
   }
}

The debug-line makes that I can see the data flowing, eg when I phone the SIM.
But it looks like the buffer isn't tested properly. The first two will work, but the last test fails. It is part of a larger string: $0,7,j,BLINK,567^ But I thought the strstr(1,2) searches for 2 in 1. And as 0,7,j,BLINK, is within the haystack I assume it wil return true. But apparently not...
The gsm.SimpleRead2() comes from GSMlib and is my altered version of gsm.SimpleRead(). Instead of printing the char, I just return it so we can buffer it in the readline function.
void SIMCOM900::SimpleRead()
{

 char datain;
 if(_cell.available()>0){
   datain=_cell.read();
   if(datain>0){
     Serial.print(datain);
   }
 }
}
char SIMCOM900::SimpleRead2()
{

 char datain;
 if(_cell.available()>0){
   datain=_cell.read();
   if(datain>0){
     return datain;
   }
 }
}

Does anyone know the answer to this?

Did you check that gsm.SimpleRead2() never returns non-printable characters (ASCII 0x00-0x1F)? That could explain why you don't see anything in the debug with Serial and the searched string can then not be found.

By the way, where does this GSM library SimpleRead2 come from? Could you provide a link?

@jfpoilpret I've added the simpleread functions and a link to the library.

So there might be some strange characters in the bffr which causes the test to fail. How can I strip a string with non-printable characters?

If there are strange characters in the GSM output, then it is quite easy to check and skip: you can use isPrintable(c) to check it and add c to bffr only in that case. This is part of standard C library, there are many other isXxxx(c) functions defined in WCharacter.h.

After a serial.read();, the data [as far as I can tell] is pretty much destroyed. You have two main options to accomplish this:

Store the data in a string when read and then reference this later. I'd do this with a global variable, that is declared outside of a method and accessible throughout your whole sketch.
I haven't read throughout your whole code, but, if you only need to read one character, you can use serial.peek();. This only works if you need the first character of the buffer.

Most likely, your only option would be the first bullet. I'd implement this by adding a method something like this:
String buffer_string_serial;

void setup() { //code here }

void loop() { //code here }

int serial_read_buffer() {
  while(serial.avaliable() > 0) {
    buffer_string_serial = buffer_string_serial + serial.peek();
    return serial.read();
  }
}

Then, just use serial_read_buffer();. That will act similar to serial.read();. The only difference is it will fill up the buffer_string_serial string. You'll have to clear that out after you used all the data so it doesn't get full.

That's what I've done with the readline() It stores everything in a global bffr. And afterwards I try to test it; but the testing doesn't work.

@stUrb Test it with expressions? I'd recommend verifying the string is exactly what you want and revisiting your testing code. Maybe print the string before testing to the serial window?

Checking for an exact match is not easy. The protocol consists of an unique integer at the end, describing a job id: $0,7,j,JOB,ID^ so everything except the ID is know and can be tested. Does Arduino/C has some kind of regular expression test/match?

@stUrb I can't find built in support in the Arduino core libraries for regex, but this library here for Arduino (with pretty good documentation) might help you.

source: Stack Exchange

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

sort: votes


text:
Need help with 2X3 matrix for braille
I'm an intermediate Arduino progammer, and I'm making an electronic braille display for my friend. You can think of this display as an array of 28x3 LEDs(one braille character contains a maximum of six (2x3 for one letter) dots so there can be 14 characters displayed at a time, including spaces) but actually instead of LEDs, there will be electrical braille cells. This will be the algorithm:

Read string (English alphabet) files from SD card
Count the letters, including spaces, until it becomes 14. Convert them into braille (2x3 for one letter) and then display them (as we will be able to display only 14 letters at a time )
When the user presses the button for the next row/page do the same process(step 2) for the next string.

So this is the complete process I want to do.
I have 5 months deadline to make it. The main problem is how I can make the code to convert and then display it. I know there are already a lot of Arduino libraries out there for displaying stranded English characters, but this is different, because I'm new to Arduino and 'C'.
Instead of losing your mind and saying this site is not for fool people like you, please guide this 17yr old what should I learn in order to make this for my friend who lost his eyesight in an accident(consider I have time of 5 months).
Do I have to build entire new Library for converting alphabet and multiplexing braille? Or is there existing code that will work.

Do you have a conceptual prototype in a language you do know?

no this will be the first time

Well, that would be a good starting point.

Why would you want braille on a display? Doesn't that defy the purpose of braille itself? Anyway, Arduino is capable of recognizing characters in an array. You simply then need to check which char it is, then display the associated dots. I suggest googling some of these things: read sd card string to char arduino, or something like this. Then find a tutorial for a display and start writing the code for only 1 letter. This way you can check if it works, if it does you can make the code for all the other letters and punctuation.

A lot of display libraries have a way to define custom font. Just create a font that shows braille dot

that will solve my complete problem, please can you tell me where can I find those libraries?

@Len He had already described that the Braille display was a 'cell'. For your information, one cell is a 2x3 element that raises different physical pins for the reader to feel with their fingertips. But for non-Braille people, he likened this cell to an LED display - very clever of him actually!

@JohnBurger Oh, that is actually pretty cool. Thanks for information :)

First of all, may I say "Thank you" for helping your friend like that? I cannot think of a better way to use an Arduino than as a driver for a Braille display like you describe!
As you know, Braille is a representation of characters into a "shape" that many systems don't recognise. Most people only encounter Braille when they press a button on an elevator or an ATM and see raised dots. Nevertheless, this is MUCH easier than the system that deaf people use: they represent whole words with a hand gesture.

I hereby challenge EVERY reader of this post to enter an elevator, or look at an ATM, and notice (and decode!) the Braille dots on the buttons. Elevators for some reason use the double coding "#1", "#2", "#3" etc. (as described in the question's graphic) when it is clearly unnecessary - of course you want to press a floor number! ATM buttons just use the 'raw' number pattern.

Because in Braille each character is converted into its own representation, you can do a VERY simple conversion. If you think about it, it is happening in computers trillions of times a day: when a computer converts a keypress into a set of pixels that represent the character on a computer screen. Your "pixels" are just a WHOLE lot simpler than the 5x7, 13x15 or font-specific conversion for the characters that normal-sighted people see.
The first thing that you need to do is define a system that converts the 2x3 array into an array of bits. Why? To make storage easier. I'm going to represent the Braille cell with a set of digits from 0 to 5:
 0   1
 2   3
 4   5

Why? Because it is then possible to "compress" the representation into a single byte of data. If you know computing well enough, you know that it runs in binary, and each digit above can be represented in a single bit, numbered 0-5.
Thus A is represented by raising the top left pin, which is the same as bit 0: which can be represented by the byte B000001 or 0x01:
X .
. .
. .

Of course a space, with nothing raised, would be represented by B000000 or 0x00.
You may not know this, and most computing people wouldn't either: the next "obvious" encoding (for B) would be B000010 or 0x02:
. X
. .
. .

But a blind person would have a serious difficulty in decoding this, since in isolation (no way of interpreting the "down" pins) it would look exactly like an 'A'. So the fact that 'B' is encoded as:
X .
X .
. .

means that the binary encoding would be B000101 or 0x05.
As a further example, the character 'I' would be
. X
X .
. .

or the byte B000110 or 0x06.
I'm not going to convert every character, but I hope that this explains things well enough for you. By giving every character its own bit pattern, you can then convert any possible string into a set of bytes for conversion by your library.
Only... there's a problem. With Braille, you need to convert numbers 0 to 9 into a special pattern. Because Braille only has 6 'bits' to choose from (and even then not every combination is "nice" for blind people to read), there is a special "flag" character to say "the following characters are digits!" (and a pattern to say "OK, back to normal letters again").
This means that there is not a one-to-one translation between an English string of characters, and the resultant string of bytes to represent those characters in Braille: you need to add extra "convert" bytes to the process. Of course these "convert" bytes can also be represented by the same bitmap as described above:
. X
. X
X X

is equal to B111010 or 0x3A.
That means that it is possible to write a function to convert a series of ASCII characters into a series of Braille bytes: you just need to provide more bytes than the string converts! This also means that you may need to use less than 14 characters from the source before you run out of room on the display...
I would love to give you my address for more help: I'm afraid that StackExchange won't let me post my e-mail address!

The elevator buttons being marked with '#1', '#2', etc could be to distinguis between say the 'Bottom/Basement' floor and the '2nd' floor.

@TwoD That makes sense! Very few elevators here have anything but numbers. I do remember seeing all sorts of things in the US - "Mezzanine", "Banquet", etc - although I don't remember the Braille (if any) those buttons had.

Each character will be 6 bits (so let's use a byte to store it) and we'll use the following bit to LED mapping
bit0   bit1
bit2   bit3
bit4   bit5

Now you just need an array of bytes where each byte signifies an ASCII character.
Your code will get the letters to display and for each one will do something like this:
byte BrailleBytes[] = {0x01, 0x05, 0xD, etc etc}; // only done the first 3 chars

byte getBrailleForCharacter(char c)
{
    int index = asc(c) - asc('A');
    return BrailleBytes[index];
}

The key to decoding it this way is to make sure you sequence your bytes in BrailleByte the same way the ASCII table does - so if you want punctuation/numbers etc then you'll have to start lower and adjust the asc('A') accordingly
Now you have the byte it is just a case of checking what bits are set and turning on the relavant LEDs.

thank you very much for answering my queries, considering I'm a beginner in arduino programming, is there any book which is specifically designed for arduino programming which can help me learning or should I just focus on normal C programming courses so that I'll be able to understand and build complex codes?

https://www.arduino.cc/ is probably the best place - lots of tutorials available.

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


text:
Multiple .ino files in the same sketch
Yeah yeah, I know people ask this type of thing a lot, but I couldn't find an answer anywhere.
I understand that you can have multiple .ino files in one sketch, but I don't just want functions and variables separated, I want functionality.
I am writing a Braille program for the NodeMCU -- It takes a message from a served website and moves servos to emulate the appropriate Braille. I want to have 2 files: one to serve the website and get input from it (website.ino), and the other one to manipulate the servos(braille.ino). The only problem is, I can't figure out where to declare/attach the servos.
I plan to have a list of servos in braille.ino that will be looped over with each servo being set to a different value. If I declare them  in website.ino (my "main" file, ie, with a setup and loop), I will have to pass them to my braille function every time. On the other hand, if I choose to declare them as globals in my braille.ino, where would I attach them? Can I have another setup in braille.ino?

I wanted the same and my solution was to use MS Visual Studio with Arduino IDE from Visual Micro.
It makes using multiple files easy and has lots of additional advantages.

just have code in the "main" .ino call a function you define in any subsequent .ino

You can use VS Code with the extension "vscode-arduino". It will allow you to manage multiple .ino files as Tabs as in the Arduino IDE does. Plus the advantages of intellisense.
Checkout the Maker.pro website for a how to: https://maker.pro/arduino/tutorial/how-to-use-visual-studio-code-for-arduino

What isn't obvious is that with Arduino, you can have normal C and C++ files in the same directory as the .ino file. These can have functions and variables inside them, and Arduino will link them into the main program too. You only need one .ino file - all the rest can be in modules with a .c or .cpp (for C++) extension.
That way, you can group "helper" functions in different files by category - for example, a BrailleServo.c file. These contain the functions and variables for just that category.
If you haven't programmed native C/C++:

Put the functions and variables in the BrailleServo.c file, and then repeat the functions' header in the BrailleServo.h file.
Inside the BrailleServo.c file, at the top, put the following line:
#include "BrailleServo.h"

Note the quotes (" "), not angle brackets (< >)
Inside the .ino file, put the same #include line. That tells the module that "there are other functions elsewhere, and these are their definitions".

The only problem? Getting the silly Arduino environment to let you add .c and .h files to that directory. You could just use Notepad, but there's a trick (if you're using Windows):

Choose File|Open…
Right-click the pane with the files in it, and choose New >|Text Document
Give it a complete name, and make sure you replace the .txt part of the name too with .c or .h. You may get the "If you change the extension, the file may be unusable" warning - just click OK.
Select the new (blank) file in the file pane, and a new tab will appear.

Note that 3. above assumes that you've told Windows File Explorer to NOT hide the extensions of known file types. I always do that - if you haven't, you'll need to. With:

Windows 10:
  In any folder's View tab, tick the File name extensions checkbox;
Windows 7:
  In Control Panel | Appearance and Personalization | Folder Options' View tab, untick Hide extensions for known file types

Here are three examples:
BrailleServo.h
//
// BrailleServo.h
//

// Call this function once in setup()
void BrailleInit();

// This function activates the six servos to form the passed-in pattern.
void BrailleShow(byte pattern);

BrailleServo.c
//
// BrailleServo.c
//

#include "BrailleServo.h"

// The number of servos
const byte NumServos = 6;

// These are the pins for the six servos
const byte servo[NumServos] = { 3, 4, 6, 7, 9, 10 };

// This initialises the six servos
void BrailleInit() {
   for (byte i=0; i<NumServos; ++i) {
      pinMode(servo[i], OUTPUT);
      // Do what else you need to do with servo[i]
   } // for
} // BrailleInit()

// This is how to use the six servos to form the passed-in pattern
void BrailleShow(byte pattern) {
   // … Complicated code here …
} // BrailleShow(pattern)

Main.ino
//
// Main.ino
//

#include "BrailleServo.h"

void setup() {
   BrailleInit();
   // Other stuff
} // setup()

void loop() {
   BrailleShow('A');
   delay(1000);
   BrailleShow('B');
   delay(1000);
} // loop()

Incidentally, for ideas you may want to check out my answer to a more generic Braille question.

Thanks so much! I guess I wasn't really thinking about having the servos do things until they were attached, but i guess that's what happens when you work overtime. I don't think I'll bother re-encoding the letters, since I already have arrays of true-false, but thanks anyway!

It is important to know that the tabs/ino files are concatenate into one by the builder. The order of the concatenation is the same as the order of tabs in IDE. First is the main ino file with the same name as the project. The rest of the files is concatenated in alphabetical order.
The concatenated ino file determines the visibility of variables. All ino files 'see' the variables in the main ino file, but variables in other ino files are visible only in ino file with names later in alphabetical order.
For functions the builder generates function prototypes to the beginning of the resulting cpp file, so as usual all functions are visible everywhere in all ino files.
One way to work with additional tabs is group is to write xySetup() and xyLoop() functions in the xy.ino file and then call this functions from the main setup() and loop(). My main Arduino project is created this way, so it is a big and complex example of this approach.
To illustrate, this is the resulting cpp file entering the cpp part of the build toolchain (scroll it to end):
#include "Arduino.h"
#define I2C_ADC121         0x50
#include <Wire.h>
extern const unsigned long EVENTS_SAVE_INTERVAL_SEC;
extern const char eventLabels[];
extern const char* eventLongLabels[];
extern const char* eventLongLabels[];
#define EVENTS_FILENAME "EVENTS.DAT"
#include <Grove_LED_Bar.h>
#include <StreamLib.h>
#include <TimeLib.h>
#include <MemoryFree.h>
#include <UIPEthernet.h>
#define ETHERNET
#include <ArduinoOTA.h>
#include <SD.h>
#define FS SD
#define Serial SerialUSB
#include "consts.h"
#define BLYNK_PRINT Serial
#define BLYNK_NO_BUILTIN // Blynk doesn't handle pins
#include <BlynkSimpleUIPEthernet.h>
#include <RTCZero.h>
#define STATS_FILENAME "STATS.DAT"

void balboaSetup() ;
void balboaReset() ;
void balboaLoop() ;
void battSettLoop() ;
boolean battSettRead(FormattedPrint& out) ;
const char* bit2s(int value, byte mask) ;
int battSettControl(boolean chargeControlOn, boolean dischargeControlOn) ;
int battSettSetLimit(byte reg, int limit) ;
void beeperLoop() ;
void alarmSound() ;
void beep() ;
void beeperTone(int freq, uint32_t time) ;
void blynkSetup() ;
void blynkLoop() ;
void updateWidgets() ;
void buttonSetup() ;
void buttonLoop() ;
void csvLogSetup() ;
void csvLogLoop() ;
void csvLogPrintJson(FormattedPrint& out) ;
void elsensSetup() ;
void elsensLoop() ;
boolean elsensCheckPump() ;
byte overheatedSecondsLeft() ;
int readElSens() ;
unsigned short elsensAnalogRead() ;
void eventsSetup() ;
void eventsLoop() ;
void eventsWrite(int newEvent, int value1, int value2) ;
boolean eventsSaved() ;
void eventsSave() ;
byte eventsRealCount() ;
void eventsPrint(FormattedPrint& stream) ;
void eventsPrint(FormattedPrint& s, int ix) ;
void eventsPrintJson(FormattedPrint& stream) ;
void eventsPrintJson(FormattedPrint& stream, int ix) ;
void eventsBlynk() ;
int eventsCompare(const void * elem1, const void * elem2) ;
void ledBarSetup() ;
void ledBarLoop() ;
void manualRunLoop() ;
byte manualRunMinutesLeft() ;
void modbusSetup() ;
boolean modbusLoop() ;
void modbusClearData() ;
boolean requestSymoRTC() ;
boolean requestInverter() ;
boolean requestMeter() ;
boolean requestBattery() ;
boolean modbusError(int err) ;
int modbusRequest(byte uid, unsigned int addr, byte len, short *regs) ;
int modbusWriteSingle(unsigned int address, int val) ;
int modbusConnection() ;
void pilotLoop() ;
unsigned short power2pwm(int power) ;
void setup() ;
void loop() ;
void shutdown() ;
void handleSuspendAndOff() ;
void clearData() ;
boolean handleAlarm() ;
boolean restHours() ;
boolean turnMainRelayOn() ;
boolean networkConnected() ;
void statsSetup() ;
void statsLoop() ;
int statsEvalCurrentPower() ;
void statsAddMilliwats() ;
void statsSave() ;
int statsConsumedPowerToday() ;
void statsPrint(FormattedPrint& out) ;
void statsPrint(FormattedPrint& out, const char *label, Stats &stats) ;
void statsPrintJson(FormattedPrint& out) ;
void statusLedSetup() ;
void statusLedLopp() ;
void statusLedShortBlink() ;
void susCalibLoop() ;
void telnetSetup() ;
void telnetLoop(boolean log) ;
void valvesBackSetup() ;
void valvesBackReset() ;
void valvesBackLoop() ;
void valvesBackStart(int v) ;
boolean valvesBackExecuted() ;
unsigned short valvesBackTempSensRead() ;
void watchdogSetup() ;
void watchdogLoop() ;
void WDT_Handler(void) ;
void webServerSetup() ;
void webServerLoop() ;
void webServerRestRequest(char cmd, ChunkedPrint& chunked) ;
void webServerServeFile(const char *fn, BufferedPrint& bp) ;
void printValuesJson(FormattedPrint& client) ;
void printAlarmJson(FormattedPrint& client) ;
const char* getContentType(const char* ext);
void wemoLoop() ;
boolean wemoPowerUsage() ;
int wemoRequest(const char* service, const char* action, const char* param, const char* value, char* response, size_t size) ;

#include "Regulator.ino"

#include "Balboa.ino"
#include "BattSett.ino"
#include "Beeper.ino"
#include "Blynk.ino"
#include "Button.ino"
#include "CsvLog.ino"
#include "ElSens.ino"
#include "Events.ino"
#include "LedBar.ino"
#include "ManualRun.ino"
#include "Modbus.ino"
#include "PowerPilot.ino"
#include "Stats.ino"
#include "StatusLed.ino"
#include "SusCalib.ino"
#include "Telnet.ino"
#include "ValvesBack.ino"
#include "Watchdog.ino"
#include "WebServer.ino"
#include "WemoInsight.ino"

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


text:
can I use Arduino cuurent-shield-sensor to measure very small voltage?
I want to measure very small voltage in small Range -100/+100 mv from a circuit,
can Arduino-shield ACS712 (max471) do that direkt ?

That chip is for measuring current, not voltage.

@user59015, why didn't you edit the original question instead of posting this new second question?

you want something like an ina219

You could use an opamp circuits to amplify and limit the signal to whatever range you like...

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


text:
Linker error when trying to use functions in separate header and source files
It is my first day of working with Arduino (it is a Due). I want to read from TMP102 through I2C. I wrote some code and it works just fine. But now I want to separate the TMP102 code from the main source code. But I get linker error:

sketch_jun15a.ino.cpp.o: In function setup':
  C:\Users\Saeid\Desktop\sketch_jun15a/sketch_jun15a.ino:62: undefined
  reference totmp102_allocate(int)' collect2.exe: error: ld returned 1
  exit status

My code is at the moment consist of 3 files:
tmp102.h
#ifndef TMP102_H
#define TMP102_H

//TP102 sensor struct
typedef struct TMP102 {
  int   address;
  float celsius;
  float fahrenheit;
} tmp102_t;

tmp102_t* tmp102_allocate(int address);

void tmp102_init_struct(tmp102_t * t, int address);

#endif

tmp102.c
#include "tmp102.h"

tmp102_t* tmp102_allocate(int address) {
  tmp102_t* t = (tmp102_t*) malloc(sizeof(tmp102_t));
  if(t) { //allocation success
    tmp102_init_struct(t, address);
    return t;
  } else {
    return 0; //null pointer
  }
}

void tmp102_init_struct(tmp102_t* t, int address) {
  t->address = address;
  t->celsius = 0.0;
  t->fahrenheit = 0.0;
}

and here is the setup function of the sketch:
#include "tmp102.h"
void setup(){

  //setup TP102 sensors
  tp_1 = tmp102_allocate(72); //error is here
  tempSensors[0] = tp_1;

  //rest of stuff...

}

I think there is no mistake in the code. There is also no option in the Arduino IDE so that I can meddle with the compiler/linker options.
All the files are inside the sketch folder. I created these files using the drop down button in the IDE...

are you including tmp102.h in the sketch, before the setup?

@Talk2 Yes of course!

Why are you not declaring the
tmp102_t* tmp102_allocate(int address) in the tmp102.h?

@Talk2 Oh sorry I have it in my code, I accidentaly removed it when pasitng the code in the question. That is not the problem :(

This is talked about here.  Evidently, the C++ compiler changes names of *.c files when compiling.  Try changing the names of your files from *.c to *.cpp so that the C++ compiler does not change the names. Then recompile.

The reason you are getting the undefined reference to  `tmp102_allocate(int)' is because your c source file is being converted to a cpp file and the function name is being mangled to support overloading etc etc. You need to flag that the functions are c code with  extern "C" blocks. If you change your header file to  the following it should compile. Alternatively, if you change the extension of your source file to .cpp you won't have any issues with name mangling but your code will probably not work (malloc). Note that by checking if __cplusplus is defined you can use this header in both cpp and c projects.
tmp102.h
#ifndef TMP102_H
#define TMP102_H

#ifdef __cplusplus
  extern "C" {
#endif

//TP102 sensor struct
typedef struct TMP102 {
  int   address;
  float celsius;
  float fahrenheit;
} tmp102_t;

 tmp102_t* tmp102_allocate(int address);

void tmp102_init_struct(tmp102_t * t, int address);

#ifdef __cplusplus
  }
#endif

#endif

Thanks a lot. I was thinking that it will be compiled by a C compiler not a C++. I just enabled the compile output and I see that it is indeed using arm-none-eabi-g++ to compile my code!

Actually you are almost there. The c file is compiled as c but the header is being included in a c++ file. It is the reference to the external c function that is being mangled not the named in the c file, which is where the mismatch occurs. The solution given here is still the correct one though. This method tells the compiler that the functions referenced are in a c file not a c++ file and disables the name mangling for them.

I gave extern "C" to the header and it does not help. it says multiple definitions found. even it does not matter if I name the file c or cpp

It compiles fine for me. Suggest you copy past the header file. Maybe your #defines arent right. And your souurce file is still .c, correct?


text:
Second I2C address not accepted
I have set up 2 DHT22 sensors and 2 BMP280 sensors with an Arduino Uno SMD R3 board. The DHTs are working fine and are outputting correct temperature and humidity values to the Serial monitor. The BMPs are connected via I2C and do not.
I assigned the standard address (0x77) to one of them, and set the other to 0x76 by placing a jumper between GND and SDO. However, in the Serial output, both devices are detected and connected (this is checked in the loop() by using the Wire library), but only one of them (0x77) shows up with the correct pressure and temperature. The other address is recognized, but it seems not to be able to transmit data.
There are already pullups on the SCL and SDA lines to the +5V terminal.
Both BMP280 sensors work, by reversing their position, it is still address 0x77 that works, however, once I change the jumper, neither works. Might this be simply an issue with the breadboard or is there an address conflict somehow? Also, I have tried several values for the pullup resistors (4.7 kOhm, 10kOhm and 140kOhm), they all seem to have the same effect.
The output looks like this:
Found address: 118 (0x76)
Found address: 119 (0x77)
Found 2 device(s).
DHT22_1: hum1 = 28.00 %, temp1 = 24.80 C
DHT22_2: hum2 = 24.80 %, temp2 = 24.70 C
BMP280_0x77: t_77 = 25.83 Cp_77 = 100039.43 Pa
BMP280_0x76: t_76 = 0.00 Cp_76 = 0.00 Pa

and I used the following code:
#include <DHT.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP280.h>

// Constants
#define DHTPIN_1 5     // pin for data
#define DHTPIN_2 4
#define DHTTYPE DHT22   // what type of sensor: DHT 22  (AM2302)

DHT dht1(DHTPIN_1, DHTTYPE); // initializes sensor
DHT dht2(DHTPIN_2, DHTTYPE); // initializes sensor

Adafruit_BMP280 bm77; // I2C
Adafruit_BMP280 bm76(0x76); // I2C

// Variables
int chk;
float hum1;  // stores humidity
float temp1; // stores temperature
float hum2;  // stores humidity
float temp2; // stores temperature

// --- Setup --- //
void setup()
{
  delay(1000);
  Serial.begin(9600);
  dht1.begin();
  dht2.begin();
  bm77.begin();
  delay(500);
  bm76.begin();
}

void loop()
{
  byte count = 0;
  Wire.begin();
  for (byte i = 1; i < 120; i++)
  {
    Wire.beginTransmission (i);
    if (Wire.endTransmission () == 0)
      {
      Serial.print ("Found address: ");
      Serial.print (i, DEC);
      Serial.print (" (0x");
      Serial.print (i, HEX);
      Serial.println (")");
      count++;
      delay (1);  // maybe unneeded?
      } // end of good response
  } // end of for loop
  Serial.print ("Found ");
  Serial.print (count, DEC);
  Serial.println (" device(s).");

  hum1 = dht1.readHumidity(); // reads and stores hum
  temp1= dht1.readTemperature(); // reads and stores temp
  hum2 = dht2.readHumidity(); // reads and stores hum
  temp2= dht2.readTemperature(); // reads and stores temp
  // serial output commands

  delay(2000); // reading needs to be delayed by at least 2000ms
  Serial.print("DHT22_1: ");
  Serial.print("hum1 = ");
  Serial.print(hum1);
  Serial.print(" %, temp1 = ");
  Serial.print(temp1);
  Serial.println(" C");

  Serial.print("DHT22_2: ");
  Serial.print("hum2 = ");
  Serial.print(hum2);
  Serial.print(" %, temp2 = ");
  Serial.print(temp2);
  Serial.println(" C");
  delay(500);
  Serial.print("BMP280_0x77: ");
  Serial.print("t_77 = ");
  Serial.print(bm77.readTemperature());
  Serial.print(" C");
  Serial.print("p_77 = ");
  Serial.print(bm77.readPressure());
  Serial.println(" Pa");
  delay(500);
  Serial.print("BMP280_0x76: ");
  Serial.print("t_76 = ");
  Serial.print(bm76.readTemperature());
  Serial.print(" C");
  Serial.print("p_76 = ");
  Serial.print(bm76.readPressure());
  Serial.println(" Pa");

  Serial.println();

}

The setup I used. red = +5V, black = GND, green = SCL, blue = SDA, yellow = DHT data lines, white = jumper between GND and SDO. Pictured is a different model of the BMP series, but in my case, I used the BMP280 and did not connect the other connectors. Edit: seems to be missing in the diagram, but of course, the positive and ground terminal are connected to the breadboard.

According to the datasheet:

SDA and SCL are not pure open drain. Both pads contain ESD protection diodes to VDDIO and GND. As the devices  does  not  perform  clock  stretching,  the  SCL  structure  is  a  high-Z  input  without  drain capability.

I'm not sure if this affects the operation with two together as you have them, but I must say that your debugging seems very thorough. :)
The words "without  drain capability" are a bit worrying. There is a thread on the Adafruit forum about this, where they suggest an I2C multiplexer.
On my page about I2C I have a schematic and code for a simple multiplexer using the CD4051 multiplexer chip (reply #11).
The schematic is this:

I am basically just interested in connecting and reading both BMP sensors simultaneously, not necessarily over I2C. However, I cant get the SPI connection to work, I2C seems like the best option so far. Is there maybe a possibility without such a multiplexer?

Judging by what you found, no. The multiplexer is, like, a $1 chip.

Alright, thank you. As an update, I have not tried it with this I2C multiplexer, but instead returned to using only one BMP sensor with an SPI connection. According to what the internet says on this topic, it seems that indeed such a multiplexer is the only reliable solution.


text:
What is the best way to init wifi communication between two devices (get IP address)?
what is the best way to init wifi communication between two devices without knowing IP of second device, let's say Raspberry Pi and ESP8266?
I want to build simple home automation system for my purpose. There will be Raspberry Pi, as heart of system and ESP8266 as controlled devices. What is best way to get them communicate? I think, the hardest think is how to get their IP address. Then it will be easy to communicate via sockets.
In next text, by RPi I mean Raspberry Pi and program in RPi will be in python (but using call of terminal commands when needed).
My idea is this: On ESP8266 will be running program, which will create WiFi Acces Point at start (on first run in network). Name (SSID) of that AP will be specific (let's say starting with ESP-AUTOMATION prefix), so Raspberry Pi will know, when new ESP device will be turned on (Raspberry Pi will repeatedly search for accesible networks). When new ESP appear, RPi will save own IP to variable and connect to newly searched network (let's say ESP-AUTOMATION-abcd). Then will RPi send to AP (ESP) it's (RPi's) IP address and local network SSID and password. Then it will disconnect, and connect back to local network (and gain it's "old" IP, which it previously saved to variable). Then ESP connect to local network with static IP and after succesfull connect, it will send to RPi it's IP address via socket (because IP addr of RPi it will already known, because RPi have send it when it served as AP). Then RPi will save that IP address. And because IP addresses (of RPi and also ESP) will be configured as static, it shouldn't change over time.
Is this good idea? Or is something of that unreal (I am at beginning of that all)?
PS: I really want completely autonomous system, so for me is not solution something like connect ESP to PC and print it's IP to serial and then it write to RPi...
Thanks for every advice/opinion.

That seems very overcomplicated to me. While not knowing, how exactly you would implement this on the ESP and Pi, you could let the Pi broadcast a special message over the network, which identifies it as your automation application server. All clients in the network will get this special message. Non-automation devices won't know, what to do with this message, thus they will ignore it. The ESP can wait for this message and when it arrives, it can save the IP, that the message came from (source IP). Then the ESP can contact the Pi by IP.

@chrisl Oh, seems very good and "simple" at the same time (y). Probably I will do it this way. THANKS!

One mechanism you could use for this is called "multicast DNS (mDNS)". This is supported by both the Raspberry Pi and the ESP8266. See also resolving Raspberry Pi address through mDNS with NodeMCU

you give the rpi a fixed IP, and on boot have the ESPs send that IP a check-in http request, which will reveal their IP to the pi.

One is a server and the other is a client.
The server do not need to know IP of the client, but the client need to know IP address of the server. See more in communication between two Arduino

But when server (RPi) will need to control clients? (For example switch lamp...)

@RozonaZoro The server will automatically get to know the client IP, when the first request from the client comes in. It would just have to save it. But the question seems to focus on the step before that. When the client doesn't know the IP of the server, how could it acquire the IP automatically?

Yes, the biggest problem is your last question. Probably I will solve it with sending broadcast message from RPi, as have suggested @chrisl.

It can be possible if the server support mDNS (Multicast DNS)


text:
ESP8266 Stops Working if I don't provide Wifi during specifc step
To test the WiFi connection I'm sharing the WiFi of my cellphone.
If I stop the WiFi sharing during the command below, the ESP8266 stops working.
It only works if I do a hardware reset.
If I don't stop the WiFi it works normally.
    if(client->POST(urlCal, host, payload))
  { RetornoPost = client->getResponseBody(); }

HTTPS Redirect (Version 2.0)
ESP8266 library version 2.4.2

Does anyone know why ESP8266 stops working?

you forgot to ask a question

If by "stops working" you mean it doesn't do whatever follows the client->POST method invocation, then your interpretation is correct and you could have found my very same information if you had read the open issues on the library before submitting your own.
If I were the author of the library I would be upset by such behavior.

Now it is working! In tests the version "2.5.0-beta2" solves this issue!

Sorry for the wrong information, but unfortunately, the error keeps occurring with "2.5.0-beta2". Sometimes ESP8826 restart when there is an error and is OK. But other times ESP88266 breaks, and I have to do a Hardware Reset.

ESP8266 library version 2.6.3, and watchdog to wait the resposnse, solve this error.


text:
How to send IR data from Arduino to USB-TTL
I have a led receiver KY-022 and led emitter KY-005, I also have a PL2303 (USB-TTL). This is the code of the issuing LED:
#include <IRremote.h>
IRsend irsend;

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

void loop()
{
   for (int i = 0; i < 50; i++) {
     irsend.sendSony(0xa90, 12); // Sony TV power code
     //Serial.print(0xa90,HEX);
     delay(40);
   }
}

The following is the connection scheme:

The output of the KY-022 I have connected to the pin RXD of the PL2303 which has a led that indicates that it receives data, however when using the HyperTerminal program to see the data I receive nothing appears.
I found similar information but they use another LED model, however I think it should work the same. What can I do?
I'm also testing with node js using the node js package, but in the console I only get non-readable characters, or something like this Buffer 00 e0 e0 e0 e0 if I do not apply toString () to the data.
This is my code in node JS.
var SerialPort = require('serialport');
var io = require('socket.io').listen(3000);

var serialPort = new SerialPort("COM9", {
    baudRate: 9600,
    parser: new SerialPort.parsers.Readline("\n")
});

io.sockets.on('connection', function(socket){
    socket.on('message', function(msg){
        console.log(msg);
    });

    socket.on('disconnected', function(){
        console.log('disconnected');
    });
});

var clearData = "";
var readData = "";

serialPort.on('open',function(){
    console.log('open');
    serialPort.on('data', function(data){
        console.log(data);
        readData += data.toString();
        io.sockets.emit('message',data);
    });
});

please post the code that you are using for receiving the IR data

I have no code for the KY-022, it is directly connected to PL2303.  I only have the node code js with which I read what enters the RX pin.

You don't have much of a clue about how IR communication works, do you? IR != serial. You need something between the receiver and your computer that decodes the incoming IR signal and converts it into something more meaningful. At the moment you're pointing a TV remote control at a fish and expecting it to bark.

You are transmitting data by encoding it using one of probably many Sony Consumer Remote Control formats and expecting to decode it using one of many possible RS232 like formats.  You will likely get something between nothing and random values.
Instead, consider sending data using only the RS232 protocols.  This is what is done in this tutorial.  It is recommended you replicate the tutorial before moving on to using a TTL to USB dongle and a computer.  This should validate the transmitter is working.  Note in the tutorial transmitter code example no IR  remote control library is used.  Only the common serial libraries.
A word regarding the tutorial.  Consider using the second of the two examples in the tutorial.  The first does not modulate the IR transmitter and will not work with commonly available IR receivers.  The second does modulate the IR transmitter and discusses how to alter the modulation to accommodate different IR receivers.


text:
Arduino Mousecontroller library doesn't work
I am working on a project with the Mousecontrol library. This causes me a lot of problems with loading the library. I imported the library but it gives me errors everytime. I think it is a mistake in the library folders but I can't seem to figure it out.
#include <MouseController.h>

// Initialize USB Controller
USBHost usb;

// Attach mouse controller to USB
MouseController mouse(usb);

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

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

void mouseMoved() {
  Serial.print("Move: ");
  Serial.print(mouse.getXChange());
  Serial.print(", ");
  Serial.println(mouse.getYChange());
}

I get this error:
Arduino: 1.6.0 (Mac OS X), Board:"Arduino Mega or Mega 2560, ATmega2560 (Mega 2560)"

In file included from /Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/MouseController.h:22:0,
                 from Muis_Bevrijding.ino:1:
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h: In member function 'virtual void HIDBoot<BOOT_PROTOCOL>::EndpointXtract(uint32_t, uint32_t, uint32_t, uint32_t, const USB_ENDPOINT_DESCRIPTOR*)':
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:474:62: error: 'UOTGHS_HSTPIPCFG_PTYPE_INTRPT' was not declared in this scope
   pipe = UHD_Pipe_Alloc(bAddress, epInfo[index].deviceEpNum, UOTGHS_HSTPIPCFG_PTYPE_INTRPT, UOTGHS_HSTPIPCFG_PTOKEN_IN, epInfo[index].maxPktSize, 10, UOTGHS_HSTPIPCFG_PBK_1_BANK);
                                                              ^
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:474:93: error: 'UOTGHS_HSTPIPCFG_PTOKEN_IN' was not declared in this scope
   pipe = UHD_Pipe_Alloc(bAddress, epInfo[index].deviceEpNum, UOTGHS_HSTPIPCFG_PTYPE_INTRPT, UOTGHS_HSTPIPCFG_PTOKEN_IN, epInfo[index].maxPktSize, 10, UOTGHS_HSTPIPCFG_PBK_1_BANK);
                                                                                ^
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:474:151: error: 'UOTGHS_HSTPIPCFG_PBK_1_BANK' was not declared in this scope
   pipe = UHD_Pipe_Alloc(bAddress, epInfo[index].deviceEpNum, UOTGHS_HSTPIPCFG_PTYPE_INTRPT, UOTGHS_HSTPIPCFG_PTOKEN_IN, epInfo[index].maxPktSize, 10, UOTGHS_HSTPIPCFG_PBK_1_BANK);
                                                                                ^
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:474:178: error: there are no arguments to 'UHD_Pipe_Alloc' that depend on a template parameter, so a declaration of 'UHD_Pipe_Alloc' must be available [-fpermissive]
   pipe = UHD_Pipe_Alloc(bAddress, epInfo[index].deviceEpNum, UOTGHS_HSTPIPCFG_PTYPE_INTRPT, UOTGHS_HSTPIPCFG_PTOKEN_IN, epInfo[index].maxPktSize, 10, UOTGHS_HSTPIPCFG_PBK_1_BANK);
                                                                                ^
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:474:178: note: (if you use '-fpermissive', G++ will accept your code, but allowing the use of an undeclared name is deprecated)
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h: In member function 'virtual uint32_t HIDBoot<BOOT_PROTOCOL>::Release()':
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:500:54: error: there are no arguments to 'UHD_Pipe_Free' that depend on a template parameter, so a declaration of 'UHD_Pipe_Free' must be available [-fpermissive]
  UHD_Pipe_Free(epInfo[epInterruptInIndex].hostPipeNum);
                                                      ^
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h: In instantiation of 'uint32_t HIDBoot<BOOT_PROTOCOL>::Release() [with unsigned char BOOT_PROTOCOL = 2u; uint32_t = long unsigned int]':
Muis_Bevrijding.ino:22:1:   required from here
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:500:54: error: 'UHD_Pipe_Free' was not declared in this scope
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h: In instantiation of 'void HIDBoot<BOOT_PROTOCOL>::EndpointXtract(uint32_t, uint32_t, uint32_t, uint32_t, const USB_ENDPOINT_DESCRIPTOR*) [with unsigned char BOOT_PROTOCOL = 2u; uint32_t = long unsigned int]':
Muis_Bevrijding.ino:22:1:   required from here
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:474:178: error: 'UHD_Pipe_Alloc' was not declared in this scope
   pipe = UHD_Pipe_Alloc(bAddress, epInfo[index].deviceEpNum, UOTGHS_HSTPIPCFG_PTYPE_INTRPT, UOTGHS_HSTPIPCFG_PTOKEN_IN, epInfo[index].maxPktSize, 10, UOTGHS_HSTPIPCFG_PBK_1_BANK);
                                                                                ^

Thanks a lot for your time!

Thanks for your reply. How can I install this? I work with an Arduino Leonardo.

USBHost
Compatible with Arduino Due only

source


text:
Dynamicly sized array as a class member
I want to create a dynamic sized array of chars as a member in a class.
This is being done inside a library that I've created.
I have the .h and the .cpp files created. I'm not sure how to declare the array in the .h file. I've tried a few things so far:
char* content;
char content[];
But these don't seem to work.
Here's what I have in my .h file:
class bufr{
    public:
    //constructor and deconstructor
    bufr(char* _chars, uint8_t _len);
    ~bufr();

    //variables
    uint8_t len;
    char content[];

};

Here's what I have in my .cpp file (this is the constructor):
bufr::bufr(char* _chars, uint8_t _len){
    char* content = new char[_len];
    content = _chars;
    len = _len;
}

I've also tried replacing the line content = _chars with:
for (int i = 0; i < _len; i++){
    content[i] = _chars[i];
}

But this also doesn't work.  When I print the content member to the serial port from within the constructor, or in the main loop it prints nonsense characters, not what I passed it.
Here's my main loop:
void loop(){
    char chars[] = "1234";
    bufr buf(chars, 4);
}

Have I explained myself well enough?  Can anyone give me a hand?
Much appreciated!
Oh, and yes, I know - in my deconstructor that's not shown, I have delete [] content
I plan on using this class nested inside another class in a few spots and hoping to take advantage of the dynamic mem allocation.  I know I can simply declare an array of fixed length, but I wanted to learn the proper way to use new and delete.
Thanks!

Actually, I lied above... I was just doing some more testing. If I print to the serial port from WITHIN the constructor the member content is printed correctly: "1234".  But, if I print from the main loop like this:  serial.println(buf.content); shows up incorrectly.  What am I doing wrong?

This is wrong on a number of levels. First in the class declaration:
char content[];

That gives you a pointer to an array of zero length.
This gives you an array of char, of zero length. This is not useful.
char* content = new char[_len];
content = _chars;

That does a new into a new variable content - not the class variable. Then you assign (overwrite) the passed pointer into content (discarding the memory you just allocated). That pointer is then discarded when the constructor ends. Perhaps using strcpy would be better.
I made up a small example based on your code which prints the correct result:
class bufr
  {
  public:
    //constructor and deconstructor
    bufr(char* chars, uint8_t len);
    ~bufr();

    //variables
    uint8_t len_;
    char * content_;
  };    // end of class bufr

bufr::bufr(char* chars, uint8_t len)
  {
  content_ = new char[len];
  memcpy (content_, chars, len);  // copy into allocated memory
  len_ = len;   // remember length
  }   // end of constructor

bufr::~bufr()
{
  delete [] content_;
} // end of destructor

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

  char chars[] = "1234 ";
  bufr buf(chars, sizeof chars);

  Serial.println (buf.content_);
} // end of setup

void loop()
{
} // end of loop

Can you explain to me why it was making a new variable content and not using the class variable?

Small example:
char * content;

void loop ()
  {
  char * content = "foo";  // makes a NEW variable
  }

In this example there are two variables named content. The one in the function "shadows" the global one. However the code below only has one variable:
char * content;

void loop ()
  {
  content = "foo";  // uses existing variable
  }

In the destructor, when you delete the pointer to the array, does this free up the memory allocated to the array? It's now free to be assigned again by something else? Or does it sit there still initialized as that array, not being able to be used again?

You aren't deleting the pointer. You are deleting the memory it points to. The pointer is now pointing to freed memory, so using it as a pointer at this stage would be wrong. You can do another new to make it point to something else.

they delete pointer and then delete[] pointer.

You misinterpreted that. You either delete pointer or delete [] pointer depending on whether pointer is an array or not. I reworked content to not be an array, thus deleting it without the brackets is correct however as it is allocated using new [] it must be deleted with delete [].

on the link posted above they say to use delete this way: delete pointer if it was a single element allocated with new or delete [] pointer to release memory allocation for arrays of elements allocated with new and a size in []'s. So in my case I want to use delete [] content_?

No, you don't want to be setting up an array in the first place. Take a look at this small example:
struct   {
  char bar [];
  } foo;

void setup()
{
Serial.begin (115200);
Serial.println ("Starting");
Serial.println (sizeof (foo));
Serial.println (sizeof (foo.bar));
}

void loop()
{
}

That prints:
Starting
0
0

The variable bar is a zero-length array. Thus the entire struct foo is also zero length. It isn't even a pointer (that would be two bytes on this platform).
It is wrong to use an array of char like that, when you want to dynamically allocate memory. Look at this:
char foo [4];

That allocates 4 bytes of memory for foo. You can't later on make it longer by doing a new.
What you want is:
char * foo;

Now you have allocated a pointer and can do a new, like this:
foo = new char [10];  // allocate 10 bytes

And then delete it:
delete [] foo;

You use the brackets on the delete, as you used them with the new.
If you allocated one char you wouldn't use brackets. eg.
char * foo;
foo = new char;  // allocate a pointer to one byte
...
delete foo;

Actually, char content[]; doesn't give you a pointer - it gives you a buffer of zero length.

Thanks for your help. Can you explain to me why it was making a new variable content and not using the class variable?

Another question regarding your answer:  In the destructor, when you delete the pointer to the array, does this free up the memory allocated to the array? It's now free to be assigned again by something else? Or does it sit there still initialized as that array, not being able to be used again?

On this page: link they show creating the dynamic array the same way as you did, but when they delete it, they delete pointer and then delete[] pointer.  Did you leave this out? Or is this necessary?

Sorry, one more edit.. I made a mistake, on the link posted above they say to use delete this way:  delete pointer if it was a single element allocated with new or delete [] pointer to release memory allocation for arrays of elements allocated with new and a size in []'s.  So in my case I want to use delete [] content_?   Thanks again!

@JohnBurger - I wrote that initially, and then changed it because the assignment seemed to work. But you are right. :)

See amended answer.

@Killerb81 You wrote char* content = new char[_len]; in the constructor. This says "I need a brand new char* variable that I'm gonna call content (never mind that there's a member called that!), and I want you to initialise it with a new pointer from the heap of _len characters." If you want to modify the member content, remove the char * at the beginning.

Thanks for taking the time guys, I really appreciate it. @NickGammon, in your example above delete foo;, even though foo is a pointer, this lets the full 10 bytes allocated to RAM (and the two bytes for the pointer?) available in RAM again?  That's the part that's confusing me and why I asked if it was correct to put the [] in the delete statement.

@JohnBurger well, isn't foo actually a pointer to a char?  Not the 10 bytes allocated for the array of chars itself.  I just don't get how using delete on a pointer frees up the 10 bytes (his example) that was allocated for the array.

Yes, foo is a pointer to char. But it got that way courtesy of foo = new char[10]; - which makes it a pointer to not only the first char, but the following 9 as well, all of them on the heap. If you did the following code: 'char c = 'A'; char *p = &c; delete [] p;thendelete[]` would be happy - while totally corrupting your heap. Shudder !

ok, I see what you mean.  So it's definitely correct to use the delete [] content ?  I just don't get why he wrote "foo is not an array so you don't use the brackets."  I don't want to inadvertently corrupt my RAM during runtime.

John Burger and Killerb81 are correct. I got confused about the brackets on the new/delete. I have corrected my answer. I had to work through this in this recent post. I just don't get why he wrote "foo is not an array so you don't use the brackets." - I was wrong. Oh well, won't be the last time. :)

Many programmers have a disjoint between a pointer and an array. Here's an explanation.
Here is a variable of type char, initialised with the value 'A':
char c = 'A';

'A' has the ASCII value of 65, so that means that there's a byte in memory that holds the value 65. Let's say that byte in memory is at address 0x2000. If you were to add 1 to that byte, it would become 66, and if you were to print it as a character, it would print B (ASCII 66).
Here is a pointer to a char, initialised with the address in memory of c:
char *p_c = &c; // Get the address of c into p_c

[Note that char *p_c = c; would be invalid: you can't initialise a pointer with a char! That'd give p_c the value 65 - not what you want!]

In Arduino, p_c represents two successive bytes of memory that together store the address of a char: in this case the value 0x2000. Where those two bytes are doesn't matter for this explanation - but trust that they too have an address...
If you were to change c into a 'Z', that would change c's contents, but not p_c's (it would still be 0x2000). But if you were to use p_c to look at the byte it was pointing to (c), then you'd see the 'Z'.

If you were to do a printf("%c", c); you'd get a 'Z'.

%c means "I've got a character as the next variable in the printf() list".

If you were to do a printf("%c", *p_c); you'd also get a 'Z'.
If you were to do a printf("%c", p_c); you'd get horrible results.

You lied to printf() - you didn't give it a one-byte character, you gave it a two-byte pointer!

Now let's move on to arrays.
Here is a variable of type char [], initialised with the value "John".
char s[] = "John";

'J' has the ASCII value 74, 'o' 112, 'h' 104, and 'n' 111. That means that in memory there are four sequential bytes with the values 74, 112, 104, 111. Let's say that those bytes are at addresses 0x3000 through 0x3003.
And here is another pointer to char, this time initialised with the address in memory of s.
char *p_s = s; // Point to s with p_s

I hate that the C language allows the above. It is one of the roots of the whole array/pointer confusion. It kind-of implies that p_s somehow gets all of "John" assigned to it. Nope!

A better statement would have been:
char *p_s = &s; // Initialise p_s with the address of s // ILLEGAL!

That gives a MUCH better idea of what's happening - alas, it's not how it's done...
But also note that neither of the above could possibly store 0x3000-0x3003 (the addresses for all of s), so they have to be satisfied with only storing the start of the string: p_s will get the value 0x3000.
Note that s does NOT have the value 0x3000 in it. That is its address, like 0x2000 was c's address (it too doesn't have 0x2000 in it). But p_s does have 0x3000 in it - and don’t forget that p_s also has its own address (I won't bother with that here).
And this is where the "equivalency" (they're not) between a pointer and an array starts to get people confused:

s[2] = 'h'; and p_s[2] = 'h'; do the same thing - but in different ways!

The first accesses 0x3002 directly.
The second needs to find out that p_s is 0x3000 and add 2 to it before it can access 0x3002.

*(p_s + 2) = 'h'; is yet a third way to do the same thing.

So now let's printf() these new variables:

printf("%c", *s); wouldn’t compile.

s is not a pointer, so you can’t dereference it with *.

printf("%c", *p_s); would print the character at where p_s was pointing.

This would print out J.

printf("%c", s[0]); would print the character at s[0].

This would print out J.

printf("%c", s); would give horrible results.

Again, you lied to printf()!

printf("%s", s); would work (but see below).

%s means "I've got a sequence of characters that I'd like you to print. I've provided the address of the first character."

printf("%s", p_s); would be identical to the previous one.

After all, the same address value was passed!

printf("%s", *p_s); would give horrible results.

Again, you lied to printf()!

But note something: you've given printf() the beginning of the string, so it can start printing. How does printf() know where the end of the string is? You didn't provide the number 4; it's not stored anywhere; how can it know when to stop?
That's where a C convention for strings steps in. By convention, when the compiler sees a string "between quotes", it stores the ASCII values of the characters, and then follows them with a 0. Not an ASCII '0' (with value 48), but an ASCII NUL (with value 0). Thus if you looked at address 0x3004 (the byte directly after John), you'd see a 0 in that memory byte. That's how printf() knows to stop printing - and yes, many a bug has resulted from forgetting to maintain a NUL at the end of a sequence of chars!
That then leads me to the sizeof() function
sizeof() always returns a constant at compile time using information that the compiler then knows about:

sizeof(c) would return 1.
sizeof(p_c) would return 2.
sizeof(p_s) would also return 2.

It is after all merely a pointer too.

sizeof(*p_c) would return 1.
sizeof(*p_s) would also return 1.

It's only pointing to a single char...

sizeof(s) would return 5.

The compiler knows what s is: an array of 5 bytes (including the final NUL).

Given a pointer, there is no (native) way to find out how large the buffer it is pointing to can be.

OK: so if you've got a char [] you can find out its size. Note that that is its maximum size - the string inside it could be a lot shorter! If you did the following:
s[3] = 0; // Overwrite the fourth character (arrays start at 0)
printf("%s", s);

[Note a better version of the first line would be s[3] = '\0'; which means "store the ASCII character 0 (NOT '0')" instead of "store the number 0".]

you'd get Joh printed out. Note:

sizeof(s) remains 5;
You can't get the length with sizeof(*p_s);
The string inside it is only 3 characters long.

So... if you've got a string buffer, or a pointer to one, how do you know how long it is? Count the number of characters until you reach a NUL - and there's already a function to do that for you: strlen().
Which now leads to the final point about pointers: dynamic allocation of memory.
The array s above was sized by the compiler at compile time: it could count the characters, add one for the NUL, and reserve the right number of bytes. You could also have written:
char s[10] = "John";

which would have reserved 10 bytes and only initialised the first 5 of them. The following would be an error:
char s[3] = "John"; // Buffer too small!

Scarily, char s[4] = "John"; works... (The compiler says to itself "No room for the NUL?! Ah well...”) Better never pass that string to strlen() or printf() then!

What if you don't know at compile time how big a string is going to be? If you know at runtime, you can ask the system for a lump of memory from the heap - a reserved area that can have chunks taken from it and returned as required. There are two ways to do this:
char *p_b = (char *)malloc(size); // Where size is a variable
char *buffer = new char[size];    // Grab 'size' new chars

The first calls malloc(), passing in the number of desired bytes. If malloc() can give those bytes it will reserve them and return a pointer to them. If it can't it will return 0. You should always test the return value! If not, you'll corrupt things horribly...
The second uses the more sophisticated new[] syntax, which is more object oriented. Notice how malloc()'s return value needed to be turned into a (char *)? That's because it doesn't know what type of pointer it's returning, so it just picks void *. new does know, so it returns the correct type - but it still may return 0 if there's no room!
Once you've got either pointer, you use them just like p_s before. There is nothing stopping you from accessing outside the boundaries of the buffer - just like there isn't for p_s! Be careful!
Oh, and once you've finished with the lump of memory, you need to return it to the heap:
free(p_b);
delete [] buffer;

If you used malloc(), return it with free(). If you used new[], return it with delete[].
And all of the above is why they invented the String object.
It manages the memory; keeps track of the string's length; lets you access and modify individual characters; lets you resize the string as needed; and gets rid of the used memory once you're finished with it. No wonder people start to use String syntax when they see string pointers...
But Strings are only useful for chars. Arrays and pointers can be of and to anything - including Strings and (GASP!) pointers! Uh oh - here we go again...

That should be a chapter in a text book!!!  Thanks @John.

@Killerb81 probably multiple chapters in a text book ;)

Thanks, people. I've proposed it as an entry in the Tag Wiki for pointer. We'll see...

I forgot to include what would happen if you wrote printf("%s", p_c); . Needless to say, you'd get a good result - and then horrible ones, as it continued to print characters until it finally got to a NUL...


text:
Passing array to library function
I'm trying to pass an array to a library (written in c++) but the error:
undefined reference to `MyLib::arrayTest(int*)'
collect2: error: ld returned 1 exit status
Error compiling.

Is being produced.
My Code Is As Follows:
Testing.ino:
MyLib test = MyLib(5,4,6);

void setup(){
    int arr[10];

    test.arrayTest(arr);

    Serial.println(arr[0]);
}

MyLib.h:
class MyLib {
    public:
        MyLib(int x, int y, int z);

        void arrayTest(int* n);

MyLib.cpp:
void arrayTest(int* n){
    n[0] = 15;
}

Any help is greatly appreciated :)

class MyLib is incomplete.

I have that correct in the code I just made a mistake when posting the question, sorry about that

This function:
void arrayTest(int* n){
    n[0] = 15;
}

is lacking the class qualifier:
void MyLib::arrayTest(int* n){
    n[0] = 15;
}

@StackNinja Easily done. I have done it myself numerous times.


text:
Controlling buzzer with assembly
I want to make a piezo buffer beeping with assembly code, but i haven't managed to yet. I have an Arduino UNO board (ATMega328p) and using avra and avrdude to build and load. The buzzer just stay silent. Here's my code:
.nolist
.include "m328pdef.inc"
.list

.equ _a = 141 ;(16000000 / 256) / 440(frequency of A) - 1

.cseg
  ;wgm02..0 = 7 (fast pwm, top = ocr0a)
  ;cs02..0 = 4 (N=256)
  ;com0b1..0 = 2 (clear on compare match, set at bottom)
  ldi r16, 0b00100011
  sts tccr0a, r16 ;need out!
  ldi r16, 0b00001100
  sts tccr0b, r16 ;need out!
  ;ocr0a = _a to obtain 440Hz
  ldi r16, 141
  out ocr0a, r16
  ;ocr0b = ocr0a/2 to obtain a duty cycle of 50%
  ldi r16, 71
  out ocr0b, r16
  ;enable output at D5 aka oc0b aka Arduino pin 5
  sbi ddrd, 5
  loop:
  rjmp loop

Wiring is good and the buzzer too, since it works with a C sketch
EDIT: I found my answer by myself (with the help of answerers). I was accessing IO ports (tccr0a and tccr0b) with sts, while i had to use out. (tccr0a and tccr0b are IO ports defined in "m328pdef.inc" as IO addresses, not as memory addresses)

A common way to gain more insight in these sort of cases is to:

compile with optimizations turned off:  -O0
tell gcc to preserve intermediate artifacts (the assembly file generated: -S or --save-temps)

I don't use gcc. I use avra

You said that the buzzer works with a C sketch. How did you compile it?

For compiling C sketches i use Arduino IDE, that uses gcc i think, but for asm compiling i use avra, the AVRStudio assembler

Right. My advice was to observe the intermediate file produced by gcc (you can tell it to preserve the assembly sources) and use them as reference for debugging your own asm program.

What does tccr0a mean? Is it an I/O address? Or a data address maybe? And what about ocr0a?

I want to make a piezo buffer beeping with assembly code - why?

Yes, tccr0a is an IO address, my error was to use sts
And I use assembly because code is faster and I save much memory, and I'm masochist

In this instance, assembly is not significantly faster. From the C program main(){TCCR0A=0x23; TCCR0B=0x0c; OCR0A=141; OCR0B=71; DDRD|=1<<5; for(;;);}, gcc generates almost exactly the assembly you wrote, except it uses out instead of sts. By writing directly in assembly, you only save the initialization done by the C runtime (13 cycles, done only once). That being said, being a masochist is a perfectly valid reason for writing assembly. Or at least I like to believe so. ;-)

I translated you program to GNU as syntax, and it works as expected: I
get a 440 Hz square wave on digital pin 5. Here is the
translated program:
#include <avr/io.h>

; I'm too lazy to always type the full name of these macros
#define io(reg) _SFR_IO_ADDR(reg)
#define mem(reg) _SFR_MEM_ADDR(reg)

_a = 141 ;(16000000 / 256) / 440(frequency of A) - 1

  ;wgm02..0 = 7 (fast pwm, top = ocr0a)
  ;cs02..0 = 4 (N=256)
  ;com0b1..0 = 2 (clear on compare match, set at bottom)
  ldi r16, 0b00100011
  sts mem(TCCR0A), r16
  ldi r16, 0b00001100
  sts mem(TCCR0B), r16
  ;ocr0a = _a to obtain 440Hz
  ldi r16, 141
  out io(OCR0A), r16
  ;ocr0b = ocr0a/2 to obtain a duty cycle of 50%
  ldi r16, 71
  out io(OCR0B), r16
  ;enable output at D5 aka oc0b aka Arduino pin 5
  sbi io(DDRD), 5
  loop:
  rjmp loop

As shown in my comment to your question, I suspect the problem is a
misunderstanding of the meaning of things like tccr0a and ocr0a.
In the translated version above, I admit I do not know what TCCR0A
and co. mean. And I need not to: I can treat these as opaque
identifiers, as the avr-libc recommends to always use them with the
macros _SFR_IO_ADDR() and _SFR_MEM_ADDR(), which provide the I/O
address and the data address of the register respectively.
I do not know how to use avra, so I cannot tell you how the get the I/O
or data address of a register. But there certainly must be a way. You
should always use the data address with sts and the I/O address with
out and sti.


text:
How to send data from arduino to Temp Controller for setting temp?
I send data from arduino by method following.
Configure the value : byte message[ ];
#include <SoftwareSerial.h>
#define RX 2
#define TX 3
int incomingByte = 0;

SoftwareSerial mySerial(RX, TX);

void setup()
{
  pinMode(5, OUTPUT);

  Serial.begin(9600);
  mySerial.begin(9600);
}

void loop()
{
  incomingByte = Serial.read();

  if (incomingByte == 's')
  {
    digitalWrite(5, HIGH);
    byte message[] = {0x01, 0x06, 0x00, 0x01, 0x02, 0x58, 0xD8, 0x90} ;
    mySerial.write(message1, sizeof(message1));
  }
}

It works. But I want to input from "Serial monitor" to set the temperature.
It does not work when input from "Serial monitor".

You're not writing any data to incomingByte and you're not detecting if data is sent towards the Arduino over serial.
You should change your void loop() into this:
void loop(){

  //Detects if something is sent over serial.
  if(Serial.available() > 0){

    //reads the byte and puts it into the incomingByte variable
    incomingByte = Serial.read();

    //below is your old code
    if (incomingByte == 's') {
      digitalWrite(5, HIGH);
      byte message[] = {0x01, 0x06, 0x00, 0x01, 0x02, 0x58, 0xD8, 0x90} ;
      mySerial.write(message1, sizeof(message1));
    }
  }
}

When you're using the serial monitor to send data towards the Arduino, also make sure the baudrate you use is the same as the Arduino's. In this case you set your baudrate to 9600 Serial.begin(9600).

Thank you. And I can send hexadecimal from "serial monitor" into the variable "byte message[ ]" ?

Yes and no. As far as I know, the serial monitor connection already sends data as HEX but it is converted automatically on both ends. So, sending HEX would actually be encrypted to HEX, sent to the Arduino, decrypted to ASCII which still gives you the original HEX value. But, I honestly don't know for sure. You should experiment, it's quite easy to make a HEX converter as well.

No, the serial monitor just sends what you type (typically ASCII) as is. No encoding is automatically applied.

@TW_JM: You can send HEX from the serial monitor, but you will have to convert the data to binary in the Arduino. That could be done with the strtol() function from avr-libc.

authors: คำผาน ขี้ดื้อ


text:
HMC5883L stops reading when x-axis value get to positive value
I've been looking for a solution for this problem for quite a time I tried different I2C libraries; like,

I2C master library using hardware TWI interface
  * Author:   Peter Fleury

But the same problem, I think my problem is in the HMC5883L_my library.
Update: I have to mention that I'm including I2C_TWSR_Check(); function to check the status of the I2C operations success in the HMC5883L library in int16_t data_read (int16_t *results_ptr); function, and as a result I get a successful operations all the time. But, the problem is when the serial monitor of the Arduino IDE is open and I'm watching the values and moving the module with different vectors, as soon as x-axis changes from -ve to +ve values, the serial monitor stops and I have to close it and open it again.
#include <avr/io.h>
#include <Arduino.h>
#include "HMC5883L_my.h"
#include "I2C.h"

int16_t results[3];

void HMC5883L_init (void)
{
  I2C_start(HMC5883L_write);
  I2C_tx(Configuration_Register_A);
  I2C_tx(0x78);
  I2C_tx(0x20);
  I2C_tx(0x00);
  I2C_stop();
}

int16_t data_read (int16_t *results_ptr)
{
  uint16_t lsb,msb;
  int16_t status_of_process = 0;

  I2C_start(HMC5883L_write);
  I2C_TWSR_Check();
  I2C_tx(Data_Output_X_MSB_Register);
  I2C_TWSR_Check();
  I2C_stop();

  I2C_start(HMC5883L_read);
  I2C_TWSR_Check();

  msb = I2C_rx();
  lsb = I2C_rx();
  I2C_TWSR_Check();

  results[0] = msb << 8 | lsb;

  Serial.print("x-axis = ");
  Serial.println(results[0]);

  msb = I2C_rx();
  lsb = I2C_rx();
  I2C_TWSR_Check();

  results[1] = msb << 8 | lsb;

  Serial.print("z-axis = ");
  Serial.println(results[1]);

  msb = I2C_rx();
  lsb = I2C_rx();
  I2C_TWSR_Check();
  results[2] = msb << 8 | lsb;

  Serial.print("y-axis = ");
  Serial.println(results[2]);
  I2C_TWSR_Check();
  I2C_stop();
  Serial.println();
  return status_of_process;
}

void HMC5883L_read_reg (uint8_t reg)
{
  uint8_t reg_dat;
  I2C_start(HMC5883L_write);
  I2C_tx(reg);
  I2C_start(HMC5883L_read);
  reg_dat = I2C_rx();
  I2C_stop();
  Serial.println(reg_dat);
}

As you can see I put I2C_TWSR_Check(); after each I2C operation to see if there's any problem during read operation but I can't see any problem when the module stops reading if x-axis value get to positive region.
This is my I2C library but I don't think there's a serious problem with it because it worked with other I2C modules without any problem.
/*
 * I2C_Library.c
 *
 * Created: 6/6/2017 12:34:39 AM
 * Author : wolfrose
 */

#include <avr/io.h>
#include <Arduino.h>
#include "I2C.h"

void I2C_init(void)
{
    //set SCL to 100kHz
    TWSR = 0x00;
    TWBR = 0x48;
    //enable TWI
    TWCR = (1<<TWEN);
}

void I2C_start(uint8_t address)
{
    TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
    while (!(TWCR & (1<<TWINT)));
    TWDR = address;
    TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
    while (!(TWCR & (1<<TWINT)));
}

void I2C_stop(void)
{
    TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN);
}

void I2C_tx(uint8_t data)
{
    TWDR = data;
    TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
    while (!(TWCR & (1<<TWINT)));
}

uint8_t I2C_rx(void)
{
    TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
    while (!(TWCR & (1<<TWINT)));
    return TWDR;
}

void I2C_TWSR_Check(void)
{
  uint8_t Status;
  Status = TWSR & 0xF8;
  switch(Status)
  {
    /////////////// MASTER TRANSMITTER //////////////
    case 0x08:
    Serial.println("Start is OK");
     break;
    case 0x10:
    Serial.println("Re start");
     break;
    case 0x18:
    Serial.println("SLA+W OK ACK");
     break;
    case 0x20:
    Serial.println("SLA+W no ACK");
     break;
    case 0x28:
    Serial.println("data TX OK ACK");
     break;
    case 0x30:
    Serial.println("data TX OK no ACK");
     break;
    case 0x38:        // arbitration lost in SLA+W or data TX
    Serial.println("arbitration lost in SLA+W or data TX");
     break;

    /////////////// MASTER RECEIVER //////////////
    case 0x40:
    Serial.println("SLA+R OK ACK");
     break;
    case 0x48:
    Serial.println("SLA+R OK NO ACK");
     break;
    case 0x50:
    Serial.println("data RX OK ACK");
     break;
    case 0x58:
    Serial.println("data RX OK NO ACK");
     break;

     default:
     Serial.println("Error");
    break;
  }
}

Have you seen this: http://hackaday.com/2017/07/29/everything-you-need-to-know-about-logic-probes/

are any of the error messages being displayed?

I don't see where the 'wait for ack/nak' on transmit nor where the 'send ack/nak' after receive is being handled.  Is that handled in the hardware?  if not, it needs to be handled in the code.

@Jot No I haven't, I'm downloading the video right now it should be interesting I'm thinking now of how powerful logic analyzers to detect errors, as with my current configuration for debugging I'm applying Arduino IDE and the serial monitor should be enough to know what is going on but actually I couldn't detect the problem.

@user3629249 No, everything looks working properly but as soon as x-axis value gets to positive it stops reading and I have to close the serial monitor and open it again to enable reading again.

@user3629249 >> 2nd comment, no in software it's 'I2C_TWSR_Check();', it's in the I2C library.

The function: I2C_TWSR_Check() does NOT wait for the ACK/NAK nor does it send that byte.  Infact the function checks the status register to see if a proper response from the slave was received, when bytes were sent.  After thinking it over, I suspect the hardware is handling the ACK/NAK communication

since your calling the I2C_TWSR_Check() function after each communication is complete, you should be seeing the output from this: Serial.println("SLA+R OK ACK"); all the time there is a successful receive communication and the output from this: Serial.println("data TX OK ACK"); all the time there is a successful transmit communication.  Your question does not mention this output.  please apply an EDIT to update

Suggest printing the whole status register before checking the bits, so you/we know what the actual status is, including when the X axis transitions from negative to positive

why is the posted code sending start and stop for each byte when sending/receiving a multibyte value.  The normal way that I2C works (after establishing communication) is the master sends start, command, stop.  then the slave sends ack then if the command was to send data then the slave sends start, data ... data, stop.  then the master sends ACK.  A very similar sequence is used when the master wants to send data.

@user3629249 First of all, thank you so much for the replies and the help. Secondly, for your first concern about ACK/NAK, well the I2C_TWSR_Check() function checks if the ACK/NAK for data or address is received or not that what I think is the process for checking ACK/NAK. But I think you mean something else, well I'm thinking of while (!(TWCR & (1<<TWINT))); where this bit is responsible for each I2C operation completion, could this bit is what you mean? Because I don't know anything about handling ACK/NAK by software or hardware.

Suggest printing the whole status register before checking the bits, so you/we know what the actual status is, including when the X axis transitions from negative to positive, I don't understand what you mean exactly, the status register is linked with the specified values for each I2C master values in the 328p datasheet, anything else is considered as an error in the last function in the I2C library.

@user3629249 why is the posted code sending start and stop for each byte when sending/receiving a multibyte value ... rest of comment, I know that, I'm actually not applying a stop function after each byte send/receive, if you see the void HMC5883L_init (void), it sends multiple bytes because one member told me that i can do it in two ways, whether to send a stop after each byte of send multiple ones with one stop. See https://arduino.stackexchange.com/questions/39373/hmc5883l-not-working-in-continuous-mode/39383#39383

Suggest reading/understanding the I2C bus specification.  Here is a link I2C

I think I'm working pretty well in my I2C library, because I applied Peter Fleury's I2C library as I mentioned in the main topic and the same problem happened. I think my problem is in the HMC5883L library.

I'm working now with a new strategy, which to apply twi main library.


text:
Is setting AVR TWCR for mega328p TWEN in each function necessary?
I found this useful website explaining for to configure and implement the TWI for mega328p, but what I found not so obvious is that in the website they set TWEN in every function, while in the datasheet C code example, they only set it in START and STOP functions.
I also find another style in Arduino Wire library, that they implement more easier functions for starting and ending the module.
This is the website, could anyone take a look and tell me if setting TWEN in each function is necessary?
Also, is it necessary to check for TWINT after sending STOP command?
http://www.embedds.com/programming-avr-i2c-interface/
Regards,

The big difference is interrupt driven or busy wait implementation of the TWI hardware module protocol. Enabling interrupts is necessary in an interrupt driven implementation while busy wait should not enable interrupts.
A busy wait implementation is much simpler but it cannot be asynchronous. An interrupt driven implementation can be asynchronous and even power down the rest of the MCU during the TWI communication. It should be noted that the Arduino Wire class is interrupt driven but synchronous.
Cheers!

OK so the interrupt driven is when I enable TWIE with the GIE. And busy wait is with disabling TWIE. So my question now is when TWINT is 0? I see it 1 all the time in the 328p datasheet. And it's mentioned that you have to wait until the bit is 0. And if you want to clear it then write 1 to this bit. So what's the value of TWINT when it's set or cleared? Regards,


text:
Read an analog signal without changing it? Or should I start over?

Hi! I'm still working on my kettle project. I want to obtain the kettle temp from the existing thermometer. I'm able to do this, but much like trying to look at an electron my circuits all reduce the voltage going to the kettle control board. This means the kettle's microcontroller (SN8P2722  SONiX) acts as if the kettle is cooler than it really is.

I don't think there is an easy way to program this microcontroller (if there is I'd love to know) -- I suspect the bad temp data will lead to overheating and hot water all over my kitchen.

Is there any way to passively obtain the voltage? I've been looking into the way that voltmeters work. Is this the right idea? is there a breakout board for this?
I really wanted to have the existing buttons still work as they always have. I've done this with power. I can press it remotely or on the kettle and I can tell of the kettle is on or off both on the control panel and remotely.

I can press all the other buttons remotely but I can't tell if it's working without knowing the kettle temp.
Maybe I should try to replace the entire control board? What would be easier? I'm something of a beginner.

Please post the schematic for the voltage-measuring (temperature measuring) part of your system. The input impedance of the analogRead should be pretty high.

I'm the last person to question somebody who's making a tea-related project, but are you ultimately attempting to control your kettle over WiFi? Do you really need to be able to turn your kettle on from your computer or phone so that it's just boiling as you walk into the kitchen and thus eliminate all that unnecessary hanging around while OH MY WORD THIS IDEA IS GENIUS.

This means the kettle's microcontroller acts as if the kettle is cooler than it really is. So what? Just "press" the button again to turn it off when you determine empirically that you have reached the right temperature.

I can press all the other buttons remotely but I can't tell if it's working without knowing the kettle temp. Why wouldn't it work? You have pressed the button, you detected the "on" LED lit up. What could go wrong now?

Where are you attaching the wire going into the analog pin on the arduino? There might be some amplification/buffering going on on the board. Try tracing where the signal goes, and then connect the wire to the trace that's going strait into the microcontroller. Also, do you have any idea what kind of sensor they use for temperature measurement?

The goal is to have hot water waiting for me when I wake up or get home to save time. The other goal is just to learn how the kettle works and learn about micros.
" So what? Just "press" the button again to turn it off" This is the kind of kettle that heats water and keeps it at a set temperature for an hour. Many teas need water that is hot but not boiling. Monitoring the kettle manually defeats the purpose and would mean my project is worse than the kettle I started with.

I will see if I can figure out the "voltage-measuring (temperature measuring) part of the system" I'm unclear if you want to know about the sensor, or if you want more information on the 5v board and display?
"Where are you attaching the wire going into the analog pin on the arduino?" I'm tapping the output to the 5v board coming from the HV board (2nd to last image)
"Also, do you have any idea what kind of sensor they use for temperature measurement?" No, it's built into the kettle base. I'll see if I can find out though. I do have and extra kettle that I can rip apart.

A JFET op amp such as the TL071 has an input impedance in the hundreds of gigaohms or higher. Using one to buffer the voltage should allow you to sample it without much interference to the existing circuit.

so the goal is to make this: https://en.wikipedia.org/wiki/Precision_rectifier

Why do you need to rectify the signal?

"Total Supply Voltage (Min) (+5V=5, +/-5V=10)" the voltage is 0-5v.  This is less than the min? I can look for one with a different set of specs.

I just need to read about this more. I'm really confused.

A circuit diagram would help muchly. However: the analog voltages are most likely DC. If they are within Arduino ADC range then reading most such would affect them minimally. If a buffer is needed then a circuit as simple as in Fig 3 in Ignacio's buffere reference should be good enoug in may cases - but a TL071 may not be the best choice, depending on voltage to be measured and available supply voltages. | Using a voltmeter (DMM) will allow you to measure voltage and advise us how it varies with temperature. ...

... BUT it would be very useful if you can provide even a partial hand drwawn cct of what you are measuring. If you do not know you are wandering around in the dark and expecting us to discern what is in the darkness by remote control. (We may be able to hazard a good guess but your help will help.
| What is range of voltage to be measured? AC or (presumably) DC. . How is it produced (temperature measurement technology). | This should be "quite easy" once a little light is shone.

The range is 0-5v. But I need to reduce it to 0-3v or my chip will fry.


text:
Connecting Arduino Uno WiFi Developer Edition to the Internet
I recently bought an Arduino Uno WiFi Developer Edition from here. Although all the other functionality appears to work (I’m able to upload/run programs, read sensors I plug in, etc.), I am not able to connect the Arduino to the internet. The Arduino has a built in ESP8266 chip which is compatible with the WiFi Link library, however, running ScanNetworks in the Arduino mac IDE (File > Examples > WiFi Link > ScanNetworks) doesn't work, nor does it print any errors. Other example files in that library don't work either. The CheckWiFiLinkFirmwareVersion program in the same library will print the welcome message "WiFi Link firmware check." but nothing after that.
I have tried every other WiFi library I could find in the library manager window (Sketch > Include Library > Manage Libraries), namely

Arduino Uno WiFi Dev Ed Library
WiFiEsp
WiFi101
WiFi

However, none of them work. Is the Arduino's WiFi chip defective, or am I doing something wrong? One reviews on the website that I bought the Arduino from said this (see lenny):

Arduino.org (which is different from arduino.cc) has not made software available to access the WiFi capabilities of this board. As far as I can tell, the wifi cannot be used. They keep saying that the software is coming soon.
See this thread on their forum: http://www.arduino.org/forums/uno/arduino-uno-wifi-arduinowifi-library-incomplete-solution-for-mqtt-tcp-udp-socket-communication-540

In summary, is the Arduino Uno WiFi Developer Edition known to be defective? If not, what am I doing wrong? If it is, could I potentially get a WiFi shield and use that instead of the built in chip? I have other shields for the Arduino (e.g. an SD card shield) that are working fine.

Re your quote : Arduino and Genuino "merged" (maybe not technically, but in essence) a few days ago when the Chairman came back and the row ended and all became lovely in the world again.  So this may well change in the near future.  It may be worth posting a question to push the issue on the Arduino forum.

Do you have access to the Webgui?
with the Webgui you can configure the wifi settings.
you do not need to upload sketches for this.
It is a good test if there is no defect.
Connect your PC Wi-Fi or with your smartphone directly to the Aduino uno wifi.
Start your browser and type in the following IP: 192.168.240.1
and now you should see the WebGUI.

The correct WiFi library for that board is here:

https://github.com/arduino-libraries/UnoWiFi-Developer-Edition-Lib

If that is not working you may have a defective board. Maybe the ESP8266 firmware is incorrect.

That GitHub link is just the repo to the "Arduino Uno WiFi Dev Ed Library", which I already installed through the library manager window in the mac desktop IDE. The ReadMacAddress example program in that library prints "Please, push the  ESP B/L button on the board and plug the USB cable before run the sketch," but after doing both things, it doesn't work. Interestingly, I see "Arduino-Uno-WiFi-823889" in the list of WiFi networks on my computer. Is that a sign that it does work and I am just doing something wrong? I bought two Arduinos, and neither can connect.

If the built in WiFi chip does not work because the Arduino Uno WiFi is new and still in development, can you recommend a good WiFi shield that has been around a while, is supported by the community, and works with the Uno and its variants?

The Arduino WiFi Shield maybe?

This popular question on Arduino.SE gives all the ways to connect an Arduino to WiFi. It mentions both the Arduino WiFi Shield and the cheaper ESP8266 chip. However, if you click through the link, it says the WiFi shield is retired. Why is that? Am I better off with an ethernet shield?

I am sure it is not defective. You just don't understand how it works, because of it's architecture. In addition the original firmware and the UnoWifiDefEd library are strange and limited. I recommend using WiFi Link firmware and library.
I currently write a community documentation for the Uno WiFi & WiFi Link


text:
Weird characters in Serial Monitor and not functioning ESP8266 ESP-12e
I did a bit of playing with my new ESP-12e, but suddenly it kind of fails on me. It gives me some weird looks it didn't give me (as much) before.

This is what the Serial Monitor prints when I try to run a very simple sketch. When I restart the module, it just adds some more of these chars.
The following is the code for that:
const int statusLED = 16;

void setup() {
  pinMode(statusLED, OUTPUT);
  digitalWrite(statusLED, HIGH);

  Serial.begin(115200);
  Serial.write("The ESP-12e has started.");
  delay(500);
}

void loop() {
  delay(1000);
  digitalWrite(statusLED, LOW);
  delay(1000);
  digitalWrite(statusLED, HIGH);
}

This doesn't even involve the WIFI...
These are my board settings:
Board: Generic ESP8266 Module
Flash mode: QIO
Flash frequency: 40MHz
CPU frequency: 80MHz
Flash size: 4M (3M SPIFFS)
Upload speed: 115200
And finally, if it might help, how I connected the module:

All connections are solid, so that shouldn't be a problem. The connection board has GPIO15 printed on it twice, but the one I connected to the LED is actually GPIO16. I noticed that the onboard LED of the ESP-12e doesn't light on anymore.
I use the CP2102 USB to UART module.
Thanks!
Rogier

It seems like maybe the firmware itself is crashing. Have you tried reflashing the device a couple of times?

The output doesn't appear to be able to have come from your code. Are the states of GPIO[0,2,15] appropriate for booting, at boot time? For running from flash, at run time?

wow, a negative for that?  Problem isn't even solved yet. rough crowd.

Yes, the GPIO pins should be connected the right way. Also, I am able to upload to the flash memory.

Yeah, weird. I don't know who would do that. I will try to flash new firmware and get back to you! Thanks for your help!

you're welcome -- my ESP8266's have been super finicky, easy to get a bad flash on em

I noticed that the onboard LED of the ESP-12e doesn't light on anymore - looking at the pictures, I hope the power coming in on the barely visible orange wire is 3.3v

Yes, that is 3.3v input from a regulator. It also should have enough power (2A).

Hi @Malachi. It's been a while, and a struggle. I just can't get it to work! The new firmware was flashed no problem (kind of), but it just won't run my sketches, nor do the default AT commands work. I think it might just be broken somehow, so I have ordered a couple of new ESP-12Fs. Hope they all keep working.

Sorry to hear this.  I'm a little surprised to hear you mention AT commands, after flashing custom firmware I would not expect any AT commands to work.  One note: not necessarily gonna solve your problem, but get a genuine FTDI based setup - those CPxxx suckers have always added a layer of problems for me.

I have downloaded the firmware from the Espressif website, so it wasn't custom. What custom firmwares are there to try?j

For example your original posted sketch would constitute a custom firmware.  If you're using the ESP8266_AT firmware from the site, then yes I would expect AT commands to work (although I have never actually flashed that firmware before =)

Ah. OK! No the custom firmwares don't work either. Although they do upload without an error.

You should be seeing a blue LED flash when you power it on at least.  If not seeing that then I'd say power delivery or a broken ESP8266.  I use this to program mine: http://www.ebay.com/itm/252225272540

The blue LED flashes when I turn it on. I'll see if the new modules work.

OK that's good news - there's hope!  Is it possible for you to upload a youtube of the flashing process?  I get a lot of clues about how successful my flash is from how the lights blink. (hopefully your CP20xx has some lights... =)

NccWarp9 is right, e.g.: void setup() { Serial.begin(115200); you have to select 115200 in your baud serial monitor option. it works also for me (nodemcu 1.0)

Check what baud rate is serial window displaying. It should be the same as defined in your code.

Thanks. But that's the same. I have tried other baud rates, but that doesn't change it.