text:
Using map for DC motor instead of servo
I am trying to use map command which is used to power servo 180 degrees as the potentiometer moves...
in fact what i want to do is just when i adjust my potentiometer to zero; stop the dc motor then after turn the pot to 512 analog value turn the motor to the left (digitalWrite(I1, HIGH); digitalWrite(I2, LOW);)and then stop when it reach 512 then when adjust the pot back to zero turn the dc motor to the right (digitalWrite(I1, HIGH); digitalWrite(I2, LOW);) but the think is what i am trying to do is exactly what we can do with the servo motor in the knob http://www.arduino.cc/en/Tutorial/Knob
I'm using a normal DC motor and l293D IC but I want to control the DC as knob method like the 200 degrees.
Code
#define E1 11    // Enable Pin for motor
#define I1 10    // Control pin a for motor
#define I2 9     // Control pin b for motor
const int analogPin = A0;
int analogValue ;

void setup() {
  pinMode(E1, OUTPUT);
  pinMode(I1, OUTPUT);
  pinMode(I2, OUTPUT);

}

void loop() {

  int analogValue = analogRead(analogPin);

  if(analogValue > 0 && analogValue < 512)  {

  analogWrite(E1, 255);
  digitalWrite(I1, HIGH);
  digitalWrite(I2, LOW);
    delay(100);
} else
  analogWrite(E1, 255);
  digitalWrite(I1, LOW);
  digitalWrite(I2, HIGH);
 }

Any chance to have a circuit diagram?

"and then stop when it reach 512" is meaningless for a DC motor unless you have a position feedback device connected to it.  Hobby type servos include an internal potentiometer for feedback.  If you are building a position control with an ordinary DC motor, you will have to mechanical link something such as an encoder or potentiometer to its shaft and implement a position control loop.


text:
Arduino uno board not detected when connected via USB no matter what OS
I was working with Arduino in Win 8.1, when suddenly it stopped work. I tried to reinstall the drivers and IDE several times, but it didn't solved.
In Win 8.1, when I plug the arduino, I get the pop up message:
USB Device Not Recognized in Windows
Also, when I try to upload a sketch, I get this error in Arduino IDE:
avrdude: ser_open(): can't open device "\\.\com5": the system cannot find the file specified

I switched to Linux (Debian Jessie 64 bits), but it also doesn't get recognized, and I getting the same error, only the port Is different.
I am guessing is a problem with avr, but I don't know what can I do about it.
Other  symptoms:

In both systems the port tool in IDE is grey, so I can't choose a port.
When I press the reset button in Arduino, nothing happens.
The led L (13) is constantly shinning. It never blinks or stops.

Solutions I tried:

Reinstall drivers
Modify the preferences.txt file to change the COM port
Fall back to a previous IDE version
Change the usb cable

See Have I bricked my Arduino Uno? Problems with uploading to board

If the port selector in the IDE is greyed out, and the OS is throwing an error, it's likely the Board is damaged. Either The firmware on the serial device or the chip is fried somehow. What's happening is that the usb part is failing, so the Com port part never works.

By chip you mean the atmega?

The FTDI or USB Atmega in charge of the usb to serial. If it's atmega based, then it's possibly you tried to program that one and everything messed up at that point.

Yeah... It seems right.

Arduino is most probably aproaching the wrong com. You can set a new com. in the IDE of arduino under settings. Change it to the available com. It might be required to find out in Windows/ system configuration for the available coms  Maybe something there is wrong.

I am not sure, where I would set the new COM. The port tool is grey. Are you talking about this?

I can not help with the Windows details because I have a Dutch version Windows 8 operational

source: Stack Exchange

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

sort: votes


text:
How to connect Arduino to headphone jack?
I would like to connect a headphone jack to my Arduino and make it as an output. I mean I would simply send some simple beeps.
I know that there is a breadboard friendly headphone jack, but I don't know how to wire it. I really don't know if I can simply connect the Arduino to the headphone jack, or I will need some resistors, etc. Will I need some voltage measurements?
Also, can I do this simply by connecting the parts of the jack ( right, left, GND) to the Arduino?
So could you please help me with this?

This project connects the headphones directly to a digital pin.  Here is the schematic:

I would, however, be more cautious and add a limiting resistor.  The output of an Arduino pin should be limited to 20mA as stated here. So, using

V=I*R
5 = 0.02 * R
R = 5 / 0.02
R = 250ohms

So I would add a ~250ohm resistor in series with the head phone.  Especially if I were debugging my code.  That is, in case I accidentally left the output pin high for an extended period of time.
The head phones should have some DC resistance.  If the sound is not loud enough you might measure that DC resistance of the head phones and subtract it from the 250 ohm resistance calculated above and use a limiting resistor of that value instead.

I had the same problem and here how I figured out a solution,
Assume your stereo jack is connected to the folowing pins;
Pin 9 = Left stereo
Pin 10 = Right stereo
GND = Ground
The solution relies on using arduinos inner circuitry.
Pin 9 and Pin 10 are our pins to control left and right stereo sounds.
We need a third pin which will be the main output source for stereo both(left and right) condition.
Say this pin be Pin8.
Connect Pin8 to Pin9 and Pin10 by two resistors of 1kOhm or similar depending on your sound level choice.
When you seet pin8 mode to OUTPUT, pin 9 and pin 10 modes to INPUT, and when you play a tone  at pin8 as tone(pin8,duration,frequency) will play stereo on the headphone.
On the other hand if pin9 is set to OUTPUT and pin10 set to INPUT, playing tone at pin8 will flow the current through right pin of the stereo jack, right sound.
Similarly if pin10 is set to OUTPUT and pin9 is set to INPUT,and tone played at the pin8 send the current through left stereo jack connected to pin9, left sound is played.
Hope this helps.

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

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


text:
Run motor for a set amount of depending of Pressure Sensor
I'm a noob when it comes to time-based coding.
I have a pressure sensor which shows me readings for when someone is sitting on a chair.
I want to turn a motor for 2 seconds when the pressure sensor says occupied
I want to turn the motor the other way for 2 seconds when the pressure sensor says empty.
Also after the motor has turned for 2 seconds, I don't want it to turn the motor at all until the reading of the pressure has changed to the other reading.
Here is my code.
#include <AFMotor.h>
AF_DCMotor motor(1,MOTOR12_64KHZ);
AF_DCMotor motor2(2,MOTOR12_64KHZ);
int fsrPin = 0;     //FSR and 10K resistor are connected to pin 0
int fsrReading;     //the analog reading from the resistor divider

bool WheelLock = true;  //controls whether the wheelchair is locked or not
long startTime = millis();
long stopTime = startTime;

void setup(void){
  Serial.begin(9600);
  motor.setSpeed(255);
  startTime = 0;
  stopTime = 5000;
}

void loop(){
  while(startTime < stopTime){
    if(onChair() == false){
      motor.run(BACKWARD);
      startTime = millis();
    }
    else{
      motor.run(FORWARD);
      startTime = millis();
    }
  }
  motor.run(RELEASE);
  Serial.println("RELEASED");
  startTime = 0;
  Serial.println(startTime);
}

bool onChair(){
  fsrReading = analogRead(fsrPin);

  if(fsrReading > 800){
    Serial.println("Wheelchair is occupied");
    WheelLock = false;
  }

  else{
    Serial.println("Wheelchair is empty");
    WheelLock = true;
  }
  delay(200);
  return WheelLock;
}

I think you want something like this:
int motorRunSecs = 2
bool chairLastState = false;
bool chairCurrState = false;
int motorDirection = FORWARD;

void loop() {
    chairCurrState = onChair();

    // if the chair occupied state has changed, then do something
    if (chairCurrState != chairOccupied) {

        // set the motor Direction based on the state of the chair
        motorDirection = ((chairCurrState) ? FORWARDS : BACKWARDS);

        // run motor for X secs
        motor.run(motorDirection);
        delay(motorRunSecs * 1000);
        motor.run(RELEASE);

        // now update the last chair state
        chairLastState = chairCurrState;
    }
}

You really want to look at the finite state machine to model your problem.
With this, you are looking at states and the transition between states.
In your problem, for example, you want to turn on a motor for a certain length of time
after the chair state changes from empty to occupied. However, in your code you are not retaining
the previous state (empty or occupied) so you cannot act when there is a state change fom empty to occupied.
Here is some rough C++ code to show you how this could work in paractice.
// states:
// ChairOccupancyState: occupied; empty
// MotorState: on; off

// pseudo code

loop() {
   if ( ChairOccupancyState == empty && onChair == true ) {
      // we have a transition from empty to occupied
      // switch motor on direction 1
      motorState = on ;
      // record time
      motor_on_at_ms  = millis() ;
      ChairOccupancyState = occupied ;
   }

   if ( ChairOccupancyState == occupiedy && onChair == false ) {
      // we have a transition from occupied to empty
      // switch motor on direction 2
      motorState = on ;
      // record time
      motor_on_at_ms  = millis()
      ChairOccupancyState = empty ;
   }

   If (motorState == on && millis() - motor_on_at_ms > 2000 ) {
      motorState == off ;
      // switch motor off
   }

}

Fairly easy.
You have to determine if the pressure has changed from its previous reading.
If it has, you can start to turn the motor for two seconds.
Once the time is up, turn the motor off.
Once you put your code in that framework, it would be much easier to code top down.


text:
How do I use a photoresistor?
I found this project and it seemed simple but now I don’t know. Please help. I tried changing the code and the wires but nothing happened.
int photoSensorPin = A0;
int redLedPin = 3;
int greenLedPin = 5;
int blueLedPin = 6;
int redLedVal = 0;
int greenLedVal = 0;
int blueLedVal = 0;
boolean isLedOn = false;

int brightness = 1023;
int darkThreshold = 50;
int changeColorTime = 900000;

long lastUpdate=0;

void setup()
{
    randomSeed(analogRead(1));
}

void loop()
{
    getBrightness();
    if (brightness < darkThreshold) {
        if (!isLedOn) {
            LedOn();
            isLedOn = true;
            lastUpdate = millis();
        } else if (millis() > lastUpdate + changeColorTime) {
            LedOn();
            isLedOn = true;
            lastUpdate = millis();
        }
    } else {
        LedOff();
        isLedOn = false;
    }
    delay(1000);
}

int getBrightness()
{
    brightness = analogRead(photoSensorPin);
    return brightness;
}

void LedOn()
{
    redLedVal = random(1,128);
    greenLedVal = random(1,128);
    blueLedVal = random(1,128);

    analogWrite(redLedPin,redLedVal);
    analogWrite(greenLedPin,greenLedVal);
    analogWrite(blueLedPin,blueLedVal);
}

void LedOff(){
    analogWrite(redLedPin,0);
    analogWrite(greenLedPin,0);
    analogWrite(blueLedPin,0);
}

1
2
3
4

Welcome to the site. There are some items to be improved about your question: copy your code instead of making screen shots, describe what you expect from your code, and exactly what does not work now.

have you tried outputting the analogread values via serial for various lighting situations, to see the actual measured values?

I fixed your pictures.  But you should delete your code pictures and enter the actual code then changing the format of the code using the "code format" button.

Thanks, and I’ve tried but I’m using my phone and it didn’t work. Plus, there’s a lot of code to paste on it.

Don't post screenshots of code. Copy the code into your question, then select it and use the {} button to format it.

Firstly, instead of screenshots, use the code inserts. Also, your question title is too broad, if you are having a problem list that.

Thank you @EjarisAbu-khdeir for entering you code instead of using pictures of your code.  It make it much easier to read and help you.

You forgot to set set the pins to output mode. In setup(), add:
pinMode(redLedPin, OUTPUT);
pinMode(greenLedPin, OUTPUT);
pinMode(blueLedPin, OUTPUT);

If that doesn't work, then you will need some debugging. Add also this
to setup():
Serial.begin(9600);

and this to loop():
Serial.println(brightness);

Look at the values printed. Do they vary significantly when the lighting
conditions change? If not, check the wiring of the LDR (it is fine in
your schematic). Do they go below and above darkThreshold? If not,
then change your threshold.

How fast does this project need to be for it to be useful?  A photo resistor can take as much as a second to react to bright to dark conditions.

Photoresistors also exhibit a certain degree of latency between
exposure to light and the subsequent decrease in resistance, usually
around 10 milliseconds. The lag time when going from lit to dark
environments is even greater, often as long as one second. This
property makes them unsuitable for sensing rapidly flashing lights

Consider testing the code by connecting A0 to 5 volts to simulate a bright condition.  Then connect A0 to ground to simulate a dark condition.

I don’t believe that the problem is the code. I’m very certain that it’s wiring. I even added a 2k resistor but I’m not sure how to wire it to the project.

The above answer has nothing to do with the code.  A photo resistor can have a very long on to off time.  How fast do you need to detect an on to off event?   Are you trying to detect a flashing light?  It may not work.  Are you trying to tell the difference between day and night.  That will probably work.

@EjarisAbu-khdeir Your wiring (as shown in the schematic) looks like it should work. If you're debugging the code it's always helpful to put some Serial.print(...) statements in there to see if it's really doing what you intended. Have you tried to output the values that come from the LDR input to see how it reacts to light and what value the threshold should have? You could also print something when your code turns the LEDs on or off (to see if that is really happening when you want it to happen).

Thank you @StarCat for actually trying to answer the question. It’s not the code but the wiring. Here, I’ll add another picture.

Also @StarCat, I tried adding code like that but it just did the same thing, nothing. The photoresistor isn’t connecting to the RGB.

@EjarisAbu-khdeir, to be absolutely clear, I am not commenting on your code at all.  I am just asking how fast you need the electronics to work.  I ask because a photo resistor can not detect fast flashing lights.  A photo resistor can only be used to detect light level changes that take longer then about a second.

@st2000 I need it to function correctly, I don’t care how fast it runs.

@EjarisAbu-khdeir, I hope you are not angry.  And I hope your project works as you want it to.

@st2000 I’m not mad and thank you, I’m just frustrated with this project and I don’t understand how to make it function.

@Edgar Bonet how do you change darkthreshold?

I think Edgar Bonet wanted you to first print out the value you are getting for brightness with the lights on and with the lights off.  Then to change this line "int darkThreshold = 50;"  from 50 to a number in between the value you are getting for brightness when the light are on and for brightness when the lights are off.

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


text:
Why doesn't this work on a Mega2560 although it works on an Arduino Uno
So, This is your code slightly altered. I am using it to read the readings of the roll and pitch of a quadcopter. I have tried using this code for a mega 2560 but it does not work in ports A0 and A1. I think it might in A5 and A6 but I am unsure how to alter this code.
THank you,
Rohan Paleja
/*  rcTiming.ino -- JW, 30 November 2015 --
 * Uses pin-change interrupts on A0-A4 to time RC pulses
 *
 * Ref: http://arduino.stackexchange.com/questions/18183/read-rc-receiver-channels-using-interrupt-instead-of-pulsein
 *
 */

#include <Streaming.h>
static   byte rcOld;        // Prev. states of inputs
volatile unsigned long rcRises[2]; // times of prev. rising edges
volatile unsigned long rcTimes[2]; // recent pulse lengths
volatile unsigned int  rcChange=0; // Change-counter
int Roll, Pitch;
// Be sure to call setup_rcTiming() from setup()
void setup_rcTiming() {
  rcOld = 0;
  pinMode(A0, INPUT);  // pin 14, A0, PC0, for pin-change interrupt
  pinMode(A1, INPUT);  // pin 15, A1, PC1, for pin-change interrupt

  PCMSK1 |= 0x0F;       // Four-bit mask for four channels
  PCIFR  |= 0x02;       // clear pin-change interrupts if any
  PCICR  |= 0x02;       // enable pin-change interrupts
}
// Define the service routine for PCI vector 1
ISR(PCINT1_vect) {
  byte rcNew = PINC & 15;   // Get low 4 bits, A0-A3
  byte changes = rcNew^rcOld;   // Notice changed bits
  byte channel = 0;
  unsigned long now = micros(); // micros() is ok in int routine
  while (changes) {
    if ((changes & 1)) {  // Did current channel change?
      if ((rcNew & (1<<channel))) { // Check rising edge
        rcRises[channel] = now;     // Is rising edge
      } else {              // Is falling edge
        rcTimes[channel] = now-rcRises[channel];
      }
    }
    changes >>= 1;      // shift out the done bit
    ++channel;
    ++rcChange;
  }
  rcOld = rcNew;        // Save new state
}

void setup() {
  Serial.begin(9600);
  Serial.println("Starting RC Timing Test");
  setup_rcTiming();
}

void loop() {
  unsigned long rcT[2]; // copy of recent pulse lengths
  unsigned int rcN;
  if (rcChange) {

    // Data is subject to races if interrupted, so off interrupts
    cli();          // Disable interrupts
    rcN = rcChange;
    rcChange = 0;       // Zero the change counter
    Roll = rcTimes[0];
    Pitch = rcTimes[1];

    sei();          // reenable interrupts

    Serial <<  " " << Roll << " " << Pitch
       << " "  << rcN << endl;

  }
  sei();            // reenable interrupts
  delay(1000);
}

Of course it doesn't. Port F doesn't support PCINT.

You are trying to do an Pin Change Interrupt on Port F (A0-A7). On the arduino Uno, this port does support PCINT but not on the Arduino Mega.
An option is to use the Port K for the PCINT. Instead of A0 and A1 you then use A8 and A9. A few little changes in the code should do the job:
void setup_rcTiming() {
rcOld = 0;
pinMode(A8, INPUT);  // pin 14, A0, PC0, for pin-change interrupt
pinMode(A9, INPUT);  // pin 15, A1, PC1, for pin-change interrupt

PCMSK2 |= 0x0F;       // Four-bit mask for four channels
PCIFR  |= 0x04;       // clear pin-change interrupts if any
PCICR  |= 0x04;       // enable pin-change interrupts
}

and
ISR(PCINT2_vect) {
byte rcNew = PINK & 15;
...
}

I have tried this code. It still does not work. I changed the code, and  plugged my signal from the receiver into A8 and A9 and no readings are being read through my serial read. Do you know why this code still isn't working? @Janw

I did edit the code because I made a mistake. In PCIFR and PCICR bit 3 should be set and not bit 2.

If I was to use A9 and A12 or A10 and A11 would I have to change anything other than pinmode?  @Janw

If you want to use the pins you mention, you should change the value of PCMSK2. In this register you can set  the pins you want to use. It takes any byte or you can set each bit separately. The least significant bit corresponds with A8, the most significant bit with A15. You can find more info about this in the datasheet of the atmega2560. Its in chapter 15 (external interrupts). PCMSK2 is on page 113.


text:
UDPSendReceiveString example using Arduino Due with ENC28J60 Ethernet Module
I was trying to learn how to use UDP protocol to use in my automation project to send commands to an Arduino Due on ethernet with an ENC28J60 breakout board which I have connected to the Due from SPI pins. I had to use another library called EthernetENC.h to use this module with the Due.
Arduino Code:
#include <EthernetENC.h>
#include <EthernetUdp.h>

#define UDP_TX_PACKET_MAX_SIZE 256

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
  0xA0, 0x36, 0xBC, 0x30, 0xC1, 0x16
};
IPAddress ip(192, 168, 137, 205);

unsigned int localPort = 8888;      // local port to listen on

// buffers for receiving and sending data
char packetBuffer[UDP_TX_PACKET_MAX_SIZE];  // buffer to hold incoming packet,
char ReplyBuffer[] = "acknowledged";        // a string to send back

// An EthernetUDP instance to let us send and receive packets over UDP
EthernetUDP Udp;

void setup() {
  // You can use Ethernet.init(pin) to configure the CS pin
Ethernet.init(10);  // Most Arduino shields
  //Ethernet.init(5);   // MKR ETH Shield
  //Ethernet.init(0);   // Teensy 2.0
  //Ethernet.init(20);  // Teensy++ 2.0
  //Ethernet.init(15);  // ESP8266 with Adafruit FeatherWing Ethernet
  //Ethernet.init(33);  // ESP32 with Adafruit FeatherWing Ethernet

  // start the Ethernet
  Ethernet.begin(mac, ip);

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

  // Check for Ethernet hardware present
  if (Ethernet.hardwareStatus() == EthernetNoHardware) {
    Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
    while (true) {
      delay(1); // do nothing, no point running without Ethernet hardware
    }
  }

  // start UDP
  Udp.begin(localPort);
}

void loop() {
  // if there's data available, read a packet
  int packetSize = Udp.parsePacket();
  if (packetSize) {
    Serial.print("Received packet of size ");
    Serial.println(packetSize);
    Serial.print("From ");
    IPAddress remote = Udp.remoteIP();
    for (int i=0; i < 4; i++) {
      Serial.print(remote[i], DEC);
      if (i < 3) {
        Serial.print(".");
      }
    }
    Serial.print(", port ");
    Serial.println(Udp.remotePort());

    // read the packet into packetBuffer
    Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
    Serial.println("Contents:");
    Serial.println(packetBuffer);

    // send a reply to the IP address and port that sent us the packet we received
    Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
    Udp.write(ReplyBuffer);
    Udp.endPacket();
  }
  delay(10);
}

Processing 3 Code:
 import hypermedia.net.*;

 UDP udp;  // define the UDP object

 void setup() {
 udp = new UDP( this, 6000 );  // create a new datagram connection on port 6000
 //udp.log( true );     // <-- printout the connection activity
 udp.listen( true );           // and wait for incoming message
 }

 void draw()
 {
 }

 void keyPressed() {
 String ip       = "192, 168, 137, 205";  // the remote IP address
 int port        = 8888;    // the destination port

 udp.send("Hello World", ip, port );   // the message to send

 }

 void receive( byte[] data ) {       // <-- default handler
 //void receive( byte[] data, String ip, int port ) {  // <-- extended handler

 for(int i=0; i < data.length; i++)
 print(char(data[i]));
 println();
 }

And this is my test setup:

After I upload the code to the Due the LinkOFF command immediately triggers and Serial.print() prints that "Ethernet cable is not connected." but this is indeed incorrect since this setup worked in other ethernet examples. But other than this message there is nothing on the Serial monitor. On the processing side, the story is even more depressing because simply nothing happens. There is just a small window opening and no matter where a click or press any key on my keyboard no string is being sent or received. I seriously don't know what to do I don't have much experience with UDP and I am trying to learn but the only responsive example in the Arduino library isn't working.
Edit:
I have connected the ENC28J60 directly to my laptop ethernet port and I chose the IP from there which was IPv4 Adress = 192.168.137.1
I also remove the linkOFF() from the original example since it was just using serial monitor for no good.

from https://github.com/JAndrassy/EthernetENC/wiki/Examples

If the Ethernet.linkStatus() is invoked too soon, it may return LinkOFF. You can do the check in setup() this way:

  if (Ethernet.linkStatus() == LinkOFF) {
    delay(500);
    if (Ethernet.linkStatus() == LinkOFF) {
      Serial.println("Ethernet cable is not connected.");
    }
  }


text:
strange behaviour with a single 7seg display
I'd like to display a sentence character by character on a single seven-segment display. What happens is that if my sentence is longer than 48 characters the central segment doesn't light up.
It works properly if I take out a letter from my string.
I have an Elegoo Uno R3, and am working on Windows, on the last version (2.0.3) of the Arduino IDE.
Is there a way to solve this issue?
Here's my code:
# include "SevSeg.h"

SevSeg  sevseg;
char    *str = "Per colpa di qualcuno non si fa credito a nessuno";
int     len = 50;

void setup(){
    byte numDigits = 1;
    byte digitPins[] = {};
    byte segmentPins[] = {6, 5, 2, 3, 4, 7, 8, 9};
    bool resistorsOnSegments = true;

    byte hardwareConfig = COMMON_CATHODE;
    sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments);
    sevseg.setBrightness(90);
}

void loop(){
  int i = 0;

  while (i < len)
  {
    sevseg.setChars(&(str[i]));
    delay(1000);
    sevseg.refreshDisplay();
    ++i;
  }
}

Thanx in advance,
Fab

Why is digitPins an empty array? You have numDigits as 1, not zero.

The tutorial states that it should be left empty for a single digit display. This is the tutorial:
circuitbasics.com/arduino-7-segment-display-tutorial
I'm gonna follow the official Arduino tutorial to see if the problem comes from the way I connected the wires to the pins:  https://arduino-france.site/7-segments/

OK. It works properly if I take out a letter from my string. - what happens if you put a lot of spaces in the string? Is something possibly overheating?

I didn't try honestly, I tried with an English sentence like "We are such stuff As dreams are made on, And our little life Is rounded with a sleep." and all worked fine.
I started anew. Thanx a lot for your support

It looks like setChars is expecting a string, not a single character.
So I would be doing something like:
  while (int i = 0; i < len; i++)
  {
    char buf [2];
    buf [0] = str[i];
    buf [1] = 0;  // null terminator
    sevseg.setChars(buf);
    sevseg.refreshDisplay();
    delay(1000);
  }

See: https://github.com/DeanIsMe/SevSeg/blob/master/SevSeg.cpp

but a pointer to char is same as pointer to c-ctring. and the setChar function uses only numDigits chars from the input string. and numDigits is 1 in this case

@NickGammon Thanx for your help, but It didn't solve the problem, or at least both approaches print the same thing, as if the problem came from the location in memory where the string is stored.

@juraj what's numDigits eactly? I found it in the setChars() function in the library but can't understand where it comes from

it is the count of seven-segment modules. the count of digits.

@Juraj thanx, I get it now.

This is the tutorial I followed:
https://www.circuitbasics.com/arduino-7-segment-display-tutorial
My wires are connected in the same way


text:
ESP32 failing to read from DHT11, MH-Z19C sensors
I got MH-Z19C (CO2 ppm) (datasheet), and DHT11 (temperature) sensors from Ebay and followed instructions online to set it up with my ESP32 board (ESP32).
I'm using a breadboard and 5V/3.3V power supply to power the sensors, while the ESP32 is linked to my PC with USB.
I'm struggling to understand the reason why I can't get a reading from my sensors. I tried countless guides online and double-checked everything multiple times.
I also tried connecting DHT11 to my board's 3.3V directly but it didn't change anything.
How do you "debug" hardware? Is there no way to know what you're doing wrong?
You have to get it exactly right or nothing works?
Serial monitor logs:
0 ppm
Failed to read from DHT sensor

MH-Z19C connections:

VIN/GND <-> Power Supply 5V +/- respectively
TX <-> ESP32 RX2
RX <-> ESP32 TX2

DHT11 connections:

Pin 1 <-> Power supply 3.3V
Pin 2 <-> 10k Ohm pull-up <-> ESP32 D2
Pin 4 <-> GND

Reference:

https://randomnerdtutorials.com/esp32-dht11-dht22-temperature-humidity-sensor-arduino-ide/
https://www.electroniclinic.com/mh-z19b-ndir-co2-sensor-with-arduino-mhz19b/
ESP32 Pinout

Libraries installed:

DHT sensor library by Adafruit
MH-Z19 by Jonathan Dempsey

// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain

// REQUIRES the following Arduino libraries:
// - DHT Sensor Library: https://github.com/adafruit/DHT-sensor-library
// - Adafruit Unified Sensor Lib: https://github.com/adafruit/Adafruit_Sensor

#include "DHT.h"
#include <SoftwareSerial.h>
#include <MHZ19.h>
#include <Wire.h>

// pin for uart reading
#define RX_PIN 16  // Rx pin which the MHZ19 Tx pin is attached to.
#define TX_PIN 17 // Tx pin which the MHZ19 Rx pin is attached to.

#define DHTPIN 2     // Digital pin connected to the DHT sensor
// Feather HUZZAH ESP8266 note: use pins 3, 4, 5, 12, 13 or 14 --
// Pin 15 can work but DHT must be disconnected during program upload.

#define DHTTYPE DHT11   // DHT 11

// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors.  This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);
MHZ19 myMHZ19;
SoftwareSerial mySerial(RX_PIN, TX_PIN);

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

  // Start Co2 sensor
  mySerial.begin(9600);                               // (Uno example) device to MH-Z19 serial start
  myMHZ19.begin(mySerial);                                // *Serial(Stream) refence must be passed to library begin().
  myMHZ19.autoCalibration();                              // Turn auto calibration ON (OFF autoCalibration(false))
}

void read_dht() {

  /////// DHT SENSOR \\\\\\
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }

  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

  Serial.print(F("Humidity: "));
  Serial.print(h);
  Serial.print(F("%  Temperature: "));
  Serial.print(t);
  Serial.print(F("C "));
  Serial.print(f);
  Serial.print(F("F  Heat index: "));
  Serial.print(hic);
  Serial.print(F("C "));
  Serial.print(hif);
  Serial.println(F("F"));

}

void loop() {
  // Wait a few seconds between measurements.
  delay(5000);

  int CO2;
  // Request CO2 (as ppm)
  CO2 = myMHZ19.getCO2();
  Serial.println(String(CO2) + " ppm");

  read_dht();
}

test only one sensor at a time ... use the example code in the library

I did try one sensor at a time. I'll have a look at the library example.

You don't need to use SoftwareSerial for the MH-Z19. You can use the Serial2 second builtin hardware serial port.

There's no dht.begin() in your setup() so your DHT11 never properly initializes. Look at some example code, like here: https://github.com/adafruit/DHT-sensor-library/blob/master/examples/DHTtester/DHTtester.ino.

Actually I am using dht.begin() currently but when copying/editing the code to SO, it got lost. I also tried with HardwareSerial without luck unfortunately.

You did a good job of giving links. You could have improved your question by showing, not just telling us, how you connected the sensors.
How do you "debug" hardware? Is there no way to know what you're doing wrong? You have to get it exactly right or nothing works?
No, that is too hard. I like to divide and conquer and test sequentially.
As already mentioned, test one sensor at a time.
To illustrate, I broke out an old ESP32 and a DHT22 and went about hooking them up as per your example.
Here are the connections:

Then I dowload the library that you had mentioned and I load their simplest example, DHTtester. If I am relying heavily on Arduino Libraries, I am relying on someone else's code, so I need to look through it so I am sure I am using it correctly.
Looking through the code, I make sure it specifies:
#define DHTPIN 2     // Digital pin connected to the DHT sensor.
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321

and I double check that I have it connected correctly . As you can see, I have the pull-up resistor on the dataline....+3.3v to one side of the resistor and the other side goes to the DHT data pin and to the ESP GPIO2 pin (see the pics?).
I double check and then run the code and the serial monitor reveals...
Humidity: 32.40%  Temperature: 23.40°C 74.12°F  Heat index: 22.64°C 72.75°F
Humidity: 32.70%  Temperature: 23.30°C 73.94°F  Heat index: 22.54°C 72.57°F
Humidity: 33.30%  Temperature: 23.30°C 73.94°F  Heat index: 22.55°C 72.60°F
Humidity: 34.10%  Temperature: 23.30°C 73.94°F  Heat index: 22.58°C 72.64°F
Humidity: 34.30%  Temperature: 23.30°C 73.94°F  Heat index: 22.58°C 72.65°F

...and if I breathe on the sensor, the RH jumps up....looks good.
If it had not have worked AND I was sure I had connected things correctly, I would have started going backwards....Can I get any program to work on the ESP, like a simple blink, there are lots of configuration options and it is easy to mess it up.
If I can get something to run, then I have to start to suspect the DHT - do I have another to test?...and so on and so forth.
Then I would repeat the same process with the CO2 sensor.
Then I would try to use them both at the same time.
Hope it helps.

So I basically replicated your setup exactly as it is with DHT and the resistor linking PIN to 3.3V in the same way you did. I'm still getting Temperature 0.00C and Humidity 0.00% so it is getting a reading, not failing, but the reading is always 0, very strange. I know that because if I disconnect the wires, then I get "error when reading temperature", "error when reading humidity". also followed this example to get info on sensors and it prints the driver version and range ok.

I'll post a picture with the wirings tomorrow.

Ok I added a photo.

I wonder if your dht11 got damaged earlier. If you had a known good one, it would be very helpful.

Not to my knowledge. I never used it before. To be honest, I'm more interested in the MH-Z19C sensor. I did some troubleshooting by following this "error codes" example from the library and it seems like the error code is  3 which stands for "Received data does not match the usual syntax expected".


text:
Esp32 fails to read MH-Z19C sensor
I'm trying to read CO2 data from a MH-Z19C sensor with an ESP32 board but I'm not getting anything. The error code from the library is 2 indicating a timeout (no data received).
Did I get the wiring wrong?
I wonder if the sensor is fried ?
Library: MH-Z19 by Jonathan Dempsey
Connections:

MH-Z19C RX to TX2 (17)
MH-Z19C TX to RX2 (16)
MH-Z19C VIN to Power Supply 5V
MH-Z19C GND to Power Supply 3V

Code:
#include <SoftwareSerial.h>
#include <MHZ19.h>
#include <Wire.h>

// pin for uart reading
#define RX_PIN 16  // Rx pin which the MHZ19 Tx pin is attached to.
#define TX_PIN 17 // Tx pin which the MHZ19 Rx pin is attached to.

MHZ19 myMHZ19;
SoftwareSerial mySerial(RX_PIN, TX_PIN);

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

  // Start Co2 sensor
  mySerial.begin(9600);                               // (Uno example) device to MH-Z19 serial start
  myMHZ19.begin(mySerial);                                // *Serial(Stream) refence must be passed to library begin().
  myMHZ19.autoCalibration();                              // Turn auto calibration ON (OFF autoCalibration(false))
}

void loop() {
  // Wait a few seconds between measurements.
  delay(5000);

  int CO2;
  // Request CO2 (as ppm)
  CO2 = myMHZ19.getCO2();
  Serial.println(String(CO2) + " ppm");

  if (myMHZ19.errorCode != RESULT_OK) {
    Serial.print("Failed to receive CO2 value: ");
    Serial.println(myMHZ19.errorCode);
  }
}

It is too difficult to follow your wiring in those pictures. A schematic diagram would be much better. You have mentioned a 3.3v and a 5v supply.  Do these share a common ground?

It is unclear how the GND are connected between the boards. It will be better to have a schematic than those pictures.

ok edited. note that the board is powered with USB while the sensor is powered by a power supply module.

I would connect the esp gnd to the z19c gnd.

Do you mean I should power the sensor with esp's GND/VIN? The issue is that the sensor needs 5v and the board only delivers 3.3V if I'm correct

It means connect PIN1 of ESP32S(GND) to pin2 of of Z19C(GND), basic 101 electronics.

Ok I connected GND of ESP32 to Power Supply GND to which PIN2 of Z19C is also connected. Is that correct? I'm still not receiving any data.

This is not a Winsen Mh-z19 sensor (or any clone following it's specs) so you won't be able to read data using a mhz19 library.
Most probably it's a HC8 sensor and someone would have to rewrite library to get data from it.
Here are specs: https://pcus.ru/download/hc8.pdf and some more info:
https://spezifisch.codeberg.page/posts/2022-08-23/co2-sensor-reverse-engineering/

how do you know it's not mh-z19?


text:
Arduino not detected
I took an Arduino from a friend yesterday but when I connect it to the laptop there is no light blinking from the Arduino and the laptop doesn't detect any device.
Is there a problem with the Arduino or is there a possibility that the USB has problems?

Try it on other computers. If it works on other computers then it's your laptop's problem. If not then the Arduino or the cable is broken.

So your Arduino or it's cable is either broken. Try with other cables. If it's still broken, you have a busted Arduino and probably need to buy a new Arduino.

Adding on to abhiarora's answer, if there are no lights at all on the Arduino, and you verify your cable is outputting power, then you may have shorted the device and need to replace the USB port diode.  On my Arduino Nano, this diode is directly under the USB-mini port, on the bottom of the board.
Picture of diode:

I replaced this on my Arduino Nano with the CDBW0520L-HF from Comchip Technology and the Arduino worked perfectly. (Link provided is from www.arrow.com).
And in case you have a Chinese Arduino Nano like me:

When you say Arduino, which product specifically are you referring to ? the Arduino UNO ?
Assuming it is the Arduino UNO (or Nano) you will need to first check if it is a genuine Arduino product or a clone (not that there is anything wrong with using a clone). Check your board for a CHIP near the USB port. See if it reads FTDI or CH340. If it reads CH340, then you have a clone. Not to worry, you can still use it as any normal Arduino, you will just need to install the appropriate drivers for the CH340 chip. A simple search for "CH340 driver" can fetch you the right results for your operating system.

Yes I am using the nano

I already bought a new one if it also doesn't blink and my computer doesn't detect it then I'll do what u suggested ....thanks

Can you check which chip is used on your existing one ? the FTDI or the CH340 ?

It's CH304 is the chip I am using

Then i would definitely insist that you try installing the drivers for CH340 and try. The standard arduino drivers that come with the Arduino IDE do not work on CH340 clones. A simple google search should give the drivers for download. If you can't find one that works, let me know and I will provide a source.

I already bought a new one but there is no harm in trying ur suggestion ...thanks for your help

Are you sure your laptop doesn't detect any device? It is possible that you need to install right driver for your arduino. The problem could be with:

Cable: Try to replace it with a working cable
Drivers Issue: You need to install driver for your Arduino. Generally, your laptop will issue warnings if it didn't find any appropriate driver for it.
USB-To-UART Bridge: This is an IC in arduino board. It needs to be working for laptop to detect your board.
Microcontroller: Since, you told us that your board is blinking, then microcontroller will be working for sure.

Can you see any part getting hotter? Have you tried with other laptop and cable?


text:
Compilation fails with non-explicit error message
I have written the following code for a project comprising an ultrasonic
distance sensor, a buzzer and a few buttons. When the distance is less
than 60 cm, the buzzer rings and stops only when the appropriate
passcode is pressed.
When I try to compile it, I get:

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

This does not give the reason for the compilation failure.
My code is below, any help would be appreciated.
#include<NewPing.h>

int r;
boolean ctr;

#define TRIGGER_PIN  10  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     9  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

//the buttons:

const int SPEAKER=8;

const int b1=4;
const int b2=5;
const int b3=6;
const int b4=7;
//variables to store previous button press and currend button press , used to eliminate switch bouncing
boolean pb1=LOW;
boolean cb1=LOW;

boolean pb2=LOW;
boolean cb2=LOW;

boolean pb3=LOW;
boolean cb3=LOW;

boolean pb4=LOW;
boolean cb4=LOW;

//variables to store numbers:

int w=0;
int x=0;
int y=0;
int z=0;

void setup() {
  // put your setup code here, to run once:
  pinMode(b1,INPUT);
  pinMode(b2,INPUT);
  pinMode(b3,INPUT);
  pinMode(b4,INPUT);

 Serial.begin(9600);

}

boolean debounce1(boolean last1)
{
   boolean current1=digitalRead(b1);
  if(last1 != current1)
  {
       delay(5);
    }
      current1=digitalRead(b1);
      return current1;
  }

boolean debounce2(boolean last2)
{
   boolean current2=digitalRead(b2);
  if(last2 != current2)
  {
      delay(5);
    }
      current2=digitalRead(b2);
      return current2;
  }

  boolean debounce3(boolean last3)
{
    boolean current3=digitalRead(b3);
  if(last3 != current3)
  {
      delay(5);
    }
      current3=digitalRead(b3);
      return current3;
  }

  boolean debounce4(boolean last4)
{
   boolean current4=digitalRead(b4);
  if(last4 != current4)
  {
      delay(5);
    }
      current4=digitalRead(b4);
      return current4;
  }

boolean distance(int o)
{
  boolean control;
  if (o<60)
    control=true;
    return control;
  }

void loop() {
  // put your main code here, to run repeatedly:
  cb1=debounce1(pb1);
  cb2=debounce2(pb2);
  cb3=debounce3(pb3);
  cb4=debounce4(pb4);

     if (pb1==LOW&&cb1==HIGH)
   {
      w++;
    }
    pb1=cb1;

    if (pb2==LOW&&cb2==HIGH)
   {
      x++;
    }
    pb2=cb2;

    if (pb3==LOW&&cb3==HIGH)
   {
      y++;
    }
    pb3=cb3;

    if (pb4==LOW&&cb4==HIGH)
   {
      z++;
    }
    pb4=cb4;

    delay(50);
    unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds   (uS).

    Serial.print(uS / US_ROUNDTRIP_CM);
    Serial.print(" ");
     int r=uS / US_ROUNDTRIP_CM;

     ctr=distance(r);

  if(ctr==true)
    tone(SPEAKER,1000);

Serial.print(w);
Serial.print(x);
Serial.print(y);
Serial.print(z);

Serial.println();

delay(100);
if(w==1&&x==3&&y==3&&z==1)
  noTone(SPEAKER);

}

There is a reason. There is always a reason. You may just have to scroll back in the output panel to see it.
Tone.cpp:536: multiple definition of `__vector_7'
NewPing/NewPing.cpp:284: first defined here
collect2: error: ld returned 1 exit status

In this case it is that you are using NewPing.h and tone().  Both of them use the same timer.
You can't use both tone() and the NewPing.h library together without first making one of them use a different timer or no timer at all.  The easiest is the NewPing.h library. As it says in the header file:
#define TIMER_ENABLED true      // Set to "false" to disable the timer ISR (if getting "__vector_7" compile errors set this to false). Default=true

So edit that header file and set true to false for that line and it should start working.


text:
I2C_Anything ++
a request for information has been formulated, how to say it?
in Ascii: i2C dialog: Tx -----> Rx ----> PCF8574
a drawing
https://nsm09.casimages.com/img/2023/02/28/23022802163423870818122937.jpg
3 elements on the i2C bus

an Arduino "Tx" to read values from an electric counter
an Arduino "Rx" to recycle the values and also to dialogue on a Rs485 bus
and a PCF8574 which receives the commands from the Arduino "Rx" to operate telestage relays

1st question:
I2C_writeAnything (foo1);
(foo2);
(foo3);
I2C_writeAnything (foo X?);

What is the maximum number of foo1 .. foo2 ...foo10 that I can put ?
Is this the right method?
or do we have to group them by pack?
2nd question:
when we use several libraries, in their sketch we find calls to #include <Wire.h>
that are added to the main sketch.
Can this be a cause of problems?
thanks
Arduino "Tx" for electrical measurements (simulation with a "random")

void loop()  {

unsigned long foo1 = random(2294967295);
unsigned long foo2 = random(2294967295);
unsigned long foo3 = random(2294967295);
unsigned long foo4 = random(2294967295);
unsigned long foo5 = random(2294967295);

if (timer0.available()) {
Wire.beginTransmission (SLAVE_ADDRESS);

I2C_writeAnything (foo1);
I2C_writeAnything (foo2);
I2C_writeAnything (foo3);
I2C_writeAnything (foo4);
I2C_writeAnything (foo5);

Wire.endTransmission ();

if (!Wire.endTransmission ()) { Serial.println ("endTransmission () : "); }
timer0.restart();
}
} /*Loop*/

//Arduino "Rx" for reading and using the Electrical values
#include <Wire.h>
#include <I2C_Anything.h>           //http://www.gammon.com.au/i2c
const byte MY_ADDRESS = 42;

volatile boolean haveData = false;
volatile unsigned long foo1;
volatile unsigned long foo2;
volatile unsigned long foo3;
volatile unsigned long foo4;

#include "PCF8574.h"                //https://github.com/RobTillaart/Arduino/tree/master/libraries/PCF8574
PCF8574 PCF27a (0x3D);  // adjust addresses i2c pcf8574

//...setup
//...loop

void receiveEvent (int howMany)  {

// if (howMany >=  4)
if (howMany >=  (sizeof foo1))    {
I2C_readAnything (foo1);
I2C_readAnything (foo2);
I2C_readAnything (foo3);
I2C_readAnything (foo4);

haveData = true;
}
}  // end of receiveEvent

What exactly do you mean with limit? The limit for data transferred in a single transaction is the size of the buffer in the Wire library. And the second question is not readable. Please edit your question to make it clear what you are asking

yes I have modified my text
thanks Chris

Can this be a cause of problems? ... you did not say anything about problems

Including libraries wil only generate problems if there is an incompatability with something in the rest of your code. Did you see any problems? Why do you think this might be a problem? You need to include Wire, since you are using it for the I2C communication.

Please format your code properly, especially repair the indentation.

The test assembly works, but after an hour or two the communication remains frozen.
A reset on the Arduino and it starts again.
I made a test by adding in the setup this line :
Wire.setWireTimeout(3000,true);
https://www.fpaynter.com/2020/07/i2c-hangup-bug-cured-miracle-of-miracles-film-at-11/
and my assembly works well, no more blocking.
I just have to find how to manage my data by 32bytes packets.

A return on the module of Electrical measurements.
with an i2C bus.
(it can be useful for other people)
No more errors, no more blocking, it purrs like a kitten.
For the structure I copied the work of Peter_n (thanks to you)
it helped me a lot:
https://forum.arduino.cc/t/i2c-not-sending-all-data-with-i2c_anything/293609
and for the :  Wire.setWireTimeout(3000,true);
not sure where to put it, it's put on both parts.
a copy of the sketches
Master_I2C_Anything_Linky_uneStructure_bigOctes.ino
  // base Written by Nick Gammon - May 2012 :
// struct de Peter_n : https://forum.arduino.cc/t/i2c-not-sending-all-data-with-i2c_anything/293609

//------------------ Dialogue on i2c bus between 2 ATMega328 - Arduino-Uno ------------
// --- 2x6 32-bit values  ou 1x 7
//------------------   functional test model ---------------------------
// Add in setup :  Wire.setWireTimeout(3000,true);

  #include <Wire.h>
  #include <I2C_Anything.h>   //http://www.gammon.com.au/i2c

  const byte SLAVE_ADDRESS = 42;

  #include "Timers.h"         //https://github.com/nettigo/Timers
  Timer timer0;   // delay

//------------  struct -------------------------
//------------ linky info ---- 7 types de variables --------//

  struct sensorData_STRUCT {
  byte sensorNumber;
    uint16_t A;   // uint16_t PAPP in VA
    uint32_t B;   // uint32_t BASE index in Wh
    uint32_t C;   // uint32_t HCHC index heures creuses en Wh
    uint32_t D;   // uint32_t HCHP Index heures pleines en Wh
    uint8_t E;    // uint8_t  IINST  Returns in Amp
    uint8_t F;    // uint8_t ISOUSC  Returns ISOUSC
    uint8_t G;    // uint8_t PTEC Periode tarifaire en cours (0 = HP, 1 = HC)
     uint8_t H;    // test
  } sensorData[1]; // [x] number of structures

//---------------------- SETUP --------------------
void setup() {
  Serial.begin (115200);
  Serial.println(F(" Master_I2C_Anything_Linky_structure_double.ino "));
  Serial.print(__DATE__); Serial.println(__FILE__);

  Wire.begin ();

  Wire.setWireTimeout(3000,true);

  // fill fixed data
  sensorData[0].sensorNumber = 0;
 // sensorData[1].sensorNumber = 1; //desactivé

  timer0.begin(SECS(3));  //delay transmission

  } /*Setup*/

//-------------------- LOOP -----------------------
  void loop()  {

//---------------- strucuture ------------
// collect new data
  sensorData[0].A = 10 ;
  sensorData[0].B = random(2000000000);
  sensorData[0].C = random(2000000000);
  sensorData[0].D =  random(2000000000) ;
  sensorData[0].E =  random(2000000000) ;
  sensorData[0].F =  random(2000000000) ; // valeur fixe
  sensorData[0].G = 70 ; // valeur fixe
  //     = 19 octes
//unsigned long : non-negative integer of  0 à 4 294 967 295 sur 32 bits de 4 octets

//------------------

  if (timer0.available()) {

 // 1; 2; choix du nbr de structre
  for( int sensor = 0; sensor < 1; sensor++)  {
    // transmit the data
    Wire.beginTransmission( SLAVE_ADDRESS);
    I2C_writeAnything( sensorData[sensor]);

    int error = Wire.endTransmission (); //(true) ?
     if( error != 0) {
      Serial.println(F("Error, no acknowledge from Slave"));
    }
  }

    timer0.restart();
  }

  } /*Loop*/

//---------------------- End pgm ----------------------------

Slave_I2C_Anything_PCF8574_4DO_uneStructure_bigOctes.ino
/*
 *  DESCRIPTION :
 *  un Arduino Uno en liaison avec un module i2c PCF8574 avec 4 Relais
 *  il recoi aussi d'un autre Arduino des valeurs en Kw pour le basculement des relay
 *
 *
 *  LIBRAIRIES:
 *    - Rob Tillaart pour PCF8574 https://github.com/RobTillaart/Arduino/tree/master/libraries/PCF8574
 *    - Nick Gammon  for bus i2c  http://www.gammon.com.au/i2c
 *    - Timers de Łukasz Tretyn   https://github.com/nettigo/Timers
 *
 *  ELEMENTS: sur le bus i2c
 *    - Expander PCF8574 avec module Metasys JC / 4DO - 0X3D  i2c adress
 *    - ATMega328  pour mesure Electrique
 *    - ATMega328  en Reception
 *
 *  MODIFICATION:
 *    -x- model de Peter_n : https://forum.arduino.cc/t/i2c-not-sending-all-data-with-i2c_anything/293609/11
 *    -o-
 *    -o-
 *
 *     RAS
*/

//------ Mars 2023 -------- Linky PCF8574 - 4DO / Bus i2c -----------------//

// -------------  Functional TEST BUS I2C -----------------------//
// une struct de 19 Octes, pour un maximum  de 32octes

//------ i2C Bus ------------
  #include <Wire.h>
  #include <I2C_Anything.h>
  const byte MY_ADDRESS = 42;

  // The struct must be the same in the Master and in the Slave
  //unsigned long:4 octet (32 bits) - max 4294967295
  struct sensorData_STRUCT {
  byte sensorNumber;
    uint16_t A;   // uint16_t PAPP in VA
    uint32_t B;   // uint32_t BASE index in Wh
    uint32_t C;   // uint32_t HCHC index heures creuses en Wh
    uint32_t D;   // uint32_t HCHP Index heures pleines en Wh
    uint8_t E;    // uint8_t  IINST  Returns in Amp
    uint8_t F;    // uint8_t ISOUSC  Returns ISOUSC
    uint8_t G;    // uint8_t PTEC Periode tarifaire en cours (0 = HP, 1 = HC)
     uint8_t H;    //
    };

/*  struct sensor2Data_STRUCT {
  byte sensor2Number;
    int G;
    int H;
    int I;
    int J;
    int K;
    int L;
    }; */

  // A special struct for the received sensor data
  volatile sensorData_STRUCT sensorDataNew;

  // A flag to indicate new data
  volatile boolean haveData = false;

  // The normal sensor data
  sensorData_STRUCT sensorData[1];  //nbr de structure [2]

//---------------- PCF8574 -------------------------------
  #include "PCF8574.h"
  PCF8574 PCF27a (0x3D);  // adjust addresses i2c pcf8574

  #define RELAY_ON  0    //
  #define RELAY_OFF 1    //

// -----------------------------------------------------------------------------
//      -----------------          SETUP          ---------------------
// -----------------------------------------------------------------------------

void setup() {

  Wire.begin (MY_ADDRESS);  // bus i2C
  Wire.onReceive (receiveEvent);

  Serial.begin (115200);
  Serial.println(F(" SlaveI2CAnythingPCF8574Structure_bigOctes "));
  Serial.print(__DATE__); Serial.println(__FILE__);

  // fill fixed data
  sensorData[0].sensorNumber = 0;

  Wire.setWireTimeout(3000,true);

  PCF27a.begin();           // i2C PCF8574

//--------- testing IsConnected i2c PCfx ------------
  Serial.print(F(" PCF8574_LIB_VERSION : \t")); Serial.println(PCF8574_LIB_VERSION);
  if (!PCF27a.begin())   {
    Serial.println(F("could not initialize..."));
    }
  if (!PCF27a.isConnected())   {
    Serial.println(F("=> not connected"));
  }
  else   {
    Serial.println(F("=> connected!!"));
    }

  } /* fin Setup */

// --------------------------------------------------------------------------
//         -----------------        LOOP      ------------------------
// --------------------------------------------------------------------------
 void loop() {

//---------------- i2C bus -------------------------------
  int sensor;  int sensor2;

    if( haveData)  {
    // New data has arrived, copy it in one of the two sensorData.
    // Disable interrups as short as possible
    // The interrupts are disabled to avoid an receiveEvent interrupt that writes new data.
    noInterrupts();
    sensor = sensorDataNew.sensorNumber;

  if( sensor == 0 || sensor == 1) {         // destination, source, size
  memcpy( &sensorData[sensor], (const void *) &sensorDataNew, sizeof( sensorData_STRUCT));

  }
  haveData = false;
  interrupts();

    printData(sensor) ; //print Data
    cmdRelay() ;        // Relay PCF8574
   }

 } /* fin Loop */

// -----------------------------------------------------------------------------
//   -------------------  Receiving messages I2C    ------------------
// -----------------------------------------------------------------------------
//howMany est le nombre d'octets reçus et par conséquent combien vous pouvez lire
//avec Wire.read(), pour un maximum de 32 octes.

 void receiveEvent( int howMany) {
  if( howMany == sizeof( sensorData_STRUCT)) {
    I2C_readAnything( sensorDataNew);
         haveData = true;
  }
  else {
    // something is wrong. Wrong number of bytes received.
    // it is possible to set a volatile variable to an error.
  }
 }

// -----------------------------------------------------------------------------
//   -------------------  Relay Control   ------------------
// -----------------------------------------------------------------------------
 void cmdRelay() {
//-------- Relay 1 ---------
  if (sensorData[0].A > 829308135 ) { PCF27a.write(0, RELAY_ON); }
  else { PCF27a.write(0, RELAY_OFF); }
     //Serial.println(PCF27a.read(0));
//-------- Relay 2 ---------
  if (sensorData[0].B > 304929158) { PCF27a.write(1, RELAY_ON); }
  else { PCF27a.write(1, RELAY_OFF); }
      //Serial.println(PCF27a.read(1));
//-------- Relay 3 ---------
  if (sensorData[0].C > 590793899 ) { PCF27a.write(2, RELAY_ON); }
  else { PCF27a.write(2, RELAY_OFF); }
     //Serial.println(PCF27a.read(2));
//-------- Relay 4 ---------
  if (sensorData[0].D > 304929158) { PCF27a.write(3, RELAY_ON); }
  else { PCF27a.write(3, RELAY_OFF); }
      //Serial.println(PCF27a.read(3));
 }

// -----------------------------------------------------------------------------
//   -------------------  Print data   ------------------
// -----------------------------------------------------------------------------
  void printData(int sensor) {

  if (sensor == 0 ) {
    Serial.print(F( "------ sensor["));
    Serial.print( sensor); Serial.println(F( "] ------"));
    Serial.print(F( "a PAPP  = ")); Serial.println( sensorData[0].A);
    Serial.print(F( "b BASE  = ")); Serial.println( sensorData[0].B);
    Serial.print(F( "c HCHC  = ")); Serial.println( sensorData[0].C);
    Serial.print(F( "d HCHP  = ")); Serial.println( sensorData[0].D);
    Serial.print(F( "e IINST = ")); Serial.println( sensorData[0].E);
    Serial.print(F( "f ISOUSC= ")); Serial.println( sensorData[0].F);
    Serial.print(F( "g PTEC  = ")); Serial.println( sensorData[0].G);
     Serial.print(F( "h test  = ")); Serial.println( sensorData[0].G);

Serial.println(sizeof( sensorData_STRUCT));
    }
    Serial.println();
  }
//------------------------------ End pgm -------------------------------------


text:
How can when the button is clicked to display its name
I need to recognize a signal from an IR remote, not to use a library for working with IR remotes/receivers. How can when the button is clicked to display its name. I have PIC12F615 microcontroller with this code: code and 5 buttons connected to him and I need recognise which button pressed. I have some code but it gives different hex codes if I pressed the same button.
byte IRpin = 2;

volatile boolean remote = false;
volatile unsigned long irCode = 0;

void remoting ()
{
  if ( remote )
  {
    remote = false;
    unsigned long T;
    for ( byte n = 0; n < 32; n ++ )
    {
      do
      {
        T = pulseIn ( IRpin, HIGH, 2200 );
      }
      while ( T < 64 );
      bitWrite ( irCode, n, T > 1120 );
    }
  }
}

void setup ()
{
  Serial.begin ( 9600 );
  Serial.println ( "\n\tReady for keyboard reading!\n" );
  pinMode ( IRpin, INPUT_PULLUP );
  attachInterrupt ( digitalPinToInterrupt ( IRpin ), remoting, FALLING );
}

void loop ()
{
  if (irCode)
  {
    Serial.println (irCode, HEX);
    irCode = 0;
  }
  delay (40);
  remote = true;
}

Schema:

the remote control may be outputting changing code

and how can I make it so that when the button is clicked to display its name

please do not ask question in a comment ... edit your post and add your question

Do you have a PIC12F615 as in your question, or a Uno as in the tags and the schematic?

You appear to be using pulseIn() in an interrupt service routine against the same pin which is used to initiate the interrupt. This is certainly odd. pulseIn() may be unreliable in an ISR and you should anyway not block an ISR.
It is certainly a novel solution to attempt to interpret what appears to be NEC IR protocol generated by that PIC.

Is either the Arduino or the PIC (or both) running on a simulator?

Both run on the simulator

Is that simulator working in real time? If not, is there any way of checking that all simulated objects are running in the same time domain, say by trying (fast) serial communications between them ?

I work in Proteus

Proteus has a logic analyser. Connect that to pin 5 of PIC and, at the same  time, pin 2 of the Arduino.  Add sample traces  and the corresponding arduino serial console output to your original question. This should help clarify if this is a PIC, Proteus or Arduino issue.

I used an oscilloscope link, yellow pin 5, blue pin 2

The function pulseIn() has this comment in the source code: "This function performs better with short pulses in noInterrupt() context" see: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/wiring_pulse.c. It is not clear if your code violates the "short pulse" rule, however, blocking an Interrupt Service Routine (in your case, the external interrupt call back routine remoting() ) for the entire length of an IR data stream is certain to cause other problems, for example, with the millis() timer.
This is in the style of your code but avoids using interrupts. It has been tested against an NEC remote control and gives repeatable results. Your code fails the same test.
byte IRpin = 2;

unsigned long irCode = 0;

void setup ()
{
  Serial.begin ( 9600 );
  Serial.println ( "\n\tReady for keyboard reading!\n" );
  pinMode ( IRpin, INPUT_PULLUP );
}

void loop () {
  while ( digitalRead ( IRpin ) );  // wait until start of first pulse
  unsigned long T;
  uint8_t validPulses = 0 ;
  for ( byte n = 0; n < 36 ; n ++ ) // enough to drop long header
  {
    T = pulseIn ( IRpin, HIGH , 12000 );  // 12ms timeout
    if ( T < 4000 && T > 400 && validPulses < 32 ) {
      // valid pulse
      bitWrite ( irCode, validPulses++, T > 1120 );
    }
  }
  if (irCode > 0 ) Serial.println (irCode, HEX);
  else Serial.println ("no code");
  irCode = 0 ;
}

is it possible to do this through the interrupt on the pin or timer interrupt?

@GoodYork Indeed there are and the one I would recommend in your case is to use the input capture mode of Timer 1. That would be non blocking, if done carefully. Does this exercise come with any other constraints such as which pin to use or that the use of pulseIn() is mandatory ? If so, add these all in to your original question. Anyway, with what you have got, you should be able to verify if the PIC is working.

Task: When writing a program, it is NOT allowed to use libraries for working with IR remotes/receivers. The signal from the receiver should be processed using an external interrupt. Your code works, here i have a code  that works through timer 1 but it doesn't work


text:
Wifly Library that works with RN171
Does anyone know of a library that works with the WiFly-RN171?
I've tried all that I could find (WiFly, WiFlyHQ and WiFlySerial) but none of them work.
WiFly and WiFlySerial both hang on WiFly.begin().
WiFlyHQ fails to enter command mode and hence proceeds no further.
I'm using the WiFly-RN171 with an Arduino Uno and Communication Shield (XBee, Bluetooth, RFID) - XBee Shield as seen below.
Has anybody gotten this configuration to work?

I have the same configuration and it works (Arduino UNO rev3)
I used WiFlyHQ library. Just be carefull with the serial.
Serial.begin(9600);
...
if (!wifly.begin(&Serial, NULL)) {
   ...

Upload with serial select then put it on USB and then open the monitor.


text:
Porting "far" flash memory access from Arduino Mega to Due
I have a project that runs on the Arduino Mega 2560 which takes up almost the complete amount of flash memory available (https://github.com/fredlcore/bsb_lan/blob/master/BSB_lan.ino). Because of this, I'm planning on migrating the project to the Arduino Due.
My main problem at the moment is to port those functions that access flash memory in the "far" memory area (>64k) for which on the one hand various _PF functions (like strncpy_PF) are provided, and on the other hand a dummy "pointer" type uint_farptr_t (which is actually uint32_t) is available.
My problems now are twofold:

While the _PF functions have specific definements for the Due which under "normal" circumstances should work without changes in the code, they expect different variable types. For example, strncpy_PF takes uint_farptr_t (i.e. uint32_t) as argument for src on the Mega, it expects a const char * on the Due. Compilation thus results in lots of errors.
For the Mega to be able to access char arrays (which are 16 Bit on the Mega) above 128k, I need a rather dirty workaround (see function calc_enum_offset() in the code linked above). Basically I need to take the memory address of a 16 Bit char pointer and make some calculations to get the final address from which I read the strings. On the Mega, I can do these calculations on the basis of uint_farptr_t and then read from the calculated memory address with pgm_read_byte_far() for example. On the Due, however, pgm_read_byte_far(addr) is translated to (*(const unsigned char *)(addr)). Again, the uint32_t type does not fit this.

Do you have any suggestions on how I should tackle these issues with the least amount of code?

the pointer type on Due has 32 bits so const char* is uint32_t. I would use ifdefs to skip use of far variants

@Juraj: Hm, uint_farptr_t on the Mega is also uint32_t, and I use it to access the memory locations of the strings in flash rom (which I calculate based on the (truncated) 16-Bit char pointer. Is there a way to access the memory locations of the const char* texts on the Due in a similar way, say by getting the memory address of the const char*, make some calculations on this address and read (e.g. a character) from the resulting memory location? This may be not/less efficient, but if it would enable me to keep most of my code running on two architectures, it would be what I'm looking for.

The Due, being ARM, is a von Neumann architecture. That means that it has no concept of "progmem", "near" or "far" pointers, etc.  There are no _P or _PF variant functions, but the Arduino core provides simple stubs as a convenience.
Instead all "flash" memory access is just simple memory accesses using const.
The best thing you can do is to use preprocessor macros to select between AVR and ARM code:
#if defined(__AVR__)
    strncpy_PF(buffer, enumstr+c, sizeof(buffer));
    buffer[sizeof(buffer)-1] = 0;
    outBufLen+=sprintf(outBuf+outBufLen,"%d - %s",val,buffer);
#else
    outBufLen += sprintf(outBuf + oufBufLen, "%d - %s", val, cmdtbl[i].enumstr);
#endif

In fact, given the huge amount of "hackiness" involved in that program with regards the cmdtbl, and the massive amounts of code that just aren't needed on the Due, it may be better to start a fresh program that is Due specific and delete the swathes of unneeded code.

Thank you for the useful example, and yes, a rewrite would certainly be the best option, but given the fact that the current user base with the Arduino Mega is several hundred users whom I would still like to provide with bugfixes without having to maintain two code-bases, that's not an option. Applying your example in varying forms to all the 100+ occurrences of the ...far... functions would make the code a complete mess. So I'm still hoping whether there is a way to solve this on the level of the functions being called and then handled there based on the respectivee architecture?

You could put everything into wrapper functions then supplicate those functions for each platform. Move the different platforms to different include files, then only include the right for for the current architecture.

That sounds like a feasible plan, thank you!


text:
How to access native USB port of Arduino Due on Synology NAS?
I would like to flash my Arduino Due from my Synology DS218+ NAS which runs on an Intel 64bit Linux-derivate platform. Previously, I was able to flash a Mega 2560 from this NAS via avrdude and currently, I am able to flash an Arduino Due via bossac through the Due's programming port. The port is registered as /dev/ttyACM0 (as was the Mega 2560) after I installed the necessary usbserial kernel module.
However, the native port is not detected likewise, or rather it is deregistered immediately:
[8336388.471865] usb 1-2: new high-speed USB device number 27 using xhci_hcd
[8336388.613119] Got empty serial number. Generate serial number from product.
[8336388.685041] cdc_acm 1-2:1.0: ttyACM0: USB ACM device
[8336389.331596] usbcore: deregistering interface driver cdc_acm

The programming port shows up like this:
[8338189.956730] usb 1-2: new full-speed USB device number 29 using xhci_hcd
[8338190.100022] usb 1-2: ep 0x82 - rounding interval to 1024 microframes, ep desc says 2040 microframes
[8338190.615513] cdc_acm 1-2:1.0: ttyACM0: USB ACM device
[8338190.621705] usbcore: registered new interface driver cdc_acm
[8338190.628534] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters

Is there anything I need to install in addition to the usbserial kernel modules to get the native port working?
P.S.: I know that the programming port is more stable, but it is also rather slow with its 115200 bps. Uploading a sketch that just takes up 50% of the Due's flash memory takes almost a minute, and if you want to see the effects of code changes, this is quite time consuming.

how is this an Arduino related question?

@jsotola: I think part of the question is whether the Due needs two different drivers for the programming and native port respectively or whether the Due needs some kind of configuration on the native port to be detected properly. Furthermore, when I posted the same question on stackoverflow as I thought it is (also) a operating system question, it was downvoted to -2 within a few hours because it was seen as an Arduino related question.


text:
Random numbers recived by wifi shield
So I am sending a web request to a server, but for some reason the result is the number: 728484804749464932504848327975131083101114118101114583213106897116101583284117101443250483268101993250484954325049585054585249327177841310671111101161011101164584121112101583211610112011647104116109108131067111110116101110116457610111010311
Any ideas?
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C Lcd(0x27, 16, 6);

#include <SPI.h>
#include <WiFi.h>

char ssid[] = "AESRO2-2.4G";
char password[] = "EA8TDKNFGE";

int status = WL_IDLE_STATUS;

WiFiClient client;

String serverReturn;

String page[]
{
  "Flashlight",
  "Message",
  "S.O.S"
};
void displayPage(int pageNumber)
{
  Lcd.clear();
  Lcd.print(page[pageNumber]);

  Lcd.setCursor(0,1);
  Lcd.print("[Open]");
  Lcd.setCursor(10, 1);
  Lcd.print("[Next]");
}
int currentPage = 0;
int lastPage = 1;

void setup()
{
  Serial.begin(9600);
  pinMode(6, OUTPUT);
  pinMode(8,OUTPUT);

  Lcd.begin();

  Lcd.print("BrickOS V5.0.0");
  digitalWrite(6, HIGH);
  delay(300);
  digitalWrite(6, LOW);

  delay(1000);

  if(WiFi.status() == WL_NO_SHIELD)
  {
    Lcd.clear();
    Lcd.print("No wifi shield");

    while(true);
  }

  String fv = WiFi.firmwareVersion();
  if(fv != "1.1.0")
  {
    String secline = fv += "->1.1.0";
    Lcd.clear();
    Lcd.print("Firmware update");
    Lcd.setCursor(0,1);
    Lcd.print(secline);

    while(true);
  }

  while(status != WL_CONNECTED)
  {
    Lcd.clear();
    Lcd.print("Connecting to");
    Lcd.setCursor(0, 1);
    Lcd.print("network...");

    status = WiFi.begin(ssid, password);

    delay(3000);
  }

  Lcd.clear();
  Lcd.print("Connected to:");
  Lcd.setCursor(0, 1);
  Lcd.print(ssid);
  delay(1000);
}

void loop()
{
  if(lastPage != currentPage)
  {
    if(currentPage > sizeof(page))
    {
      currentPage = 0;
    }
    displayPage(currentPage);
  }
  lastPage = currentPage;

  serverReturn = "";
  while(client.available()) {
    serverReturn += client.read();
  }
  client.stop();
  if(client.connect("www.nightfall.huskyclick.info", 80))
  {
    client.println("GET /msg.php?action=check&ID=1 HTTP/1.1");
    client.println("Host: nightfall.huskyclick.info");
    client.println();
  }
  else
  {
    Lcd.clear();
    Lcd.print("Failed to check");
    Lcd.setCursor(0, 1);
    Lcd.print("for messages");
  }

  Serial.println(serverReturn);

  if(serverReturn != "false" && serverReturn != "")
  {
    digitalWrite(8, HIGH);

    Lcd.clear();
    Lcd.print("Message received!");

    digitalWrite(6, HIGH);
    delay(500);
    digitalWrite(6, LOW);

    delay(1000);

    Lcd.clear();
    Lcd.print(serverReturn);

    delay(5000);
  }

  delay(5000);
}

Yes, that's what you get when you append an int to a String.

The fault lies here:
while(client.available()) {
  serverReturn += client.read();
}

client.read() returns an integer. That integer is either the ASCII code of the next character in the buffer, or -1 if there are no characters in the buffer left to read.
You then append that integer to the end of a String which gets converted to the ASCII representation of that integer before being appended.
So the string HTTP, for instance, which is ASCII characters 72, 84 (twice) and 80 ends up as "72848480".
Instead you need to cast the integer to a char before appending:
serverReturn += (char)client.read();

Or better still don't use any String variables at all and parse the data as it comes in pulling out any information you need to at the time it arrives.


text:
Missing Libraries make no sense
I've never much issue importing a library to my master sketchbook location, restarting Arduino, then using the library examples. Today is a different story:

I'm loading RCLib which is part of this ArduinoLibraries family
RCLib requires PinChangeInt

So everything is in my sketchbook location right? Arduino > Preferences > Sketchbook Location
Still I'm getting compiler errors about missing libraries:
/Users/Jackson/Documents/Arduino/ArduinoLibraries-master/RCLib/Examples/Maga6ChanelsA8_A13/Maga6ChanelsA8_A13.ino:7:86: fatal error: PinChangeInt.h: No such file or directory
 #include "PinChangeInt.h"

I've even tried #include <PinChangeInt.h> Which makes more sense since this is a system library.
What is going on here?
The sketch I'm trying to run:
/**This is an example of using the RCLib with a mega and pinchangeint
 * This example isprovided as is by Jantje
 * Congratualtions, constructive feedback and I like it can be send to eclipse@baeyens.it
 **/

#define NUM_RC_CHANNELS 6 //You need to specify how many pins you want to use
#include "PinChangeInt.h"  //If you need pinchangeint you need to include this header
const uint8_t RC_Channel_Pin[NUM_RC_CHANNELS]={
  A8,A9,A10,A11,A12,A13};//Here I specify I want to listen to pins A8 to A13 of my mega

uint16_t RC_Channel_Value[NUM_RC_CHANNELS]; //This variable will contain the values read from the RC signal
#include "RCLib.h" //This include needs all declarations above. Do not try to move it up or it won't compile

Arduino v1.6.9 | OSX 10.11.4

The libraries should be in sketchbook location -> libraries. Try using #include <PinChangeInt.h> (note the less-than / greater-than).

I had downloaded PinChangeInterrupt through Arduino
Sketch > Include Library > Manage Libraries... > Filter your search... > PinChangeInterrupt > Install
I thought this is all I needed but I was wrong. This differs from the popular PinChangeInt library. Ultimately the file names where slightly different which is why my file was showing as missing. I found this out by manually looking at the file names in the library I was trying to used and comparing them against my includes.


text:
How can I move these global variables to be
I'm taking a sample I found on the web about how to get ROS and arduino to communicated together over serial. I have the sample working and now I'm moving the idea of the sample into my OOP project and am running into some trouble.
My sketch works but when I move a certain global variable to a protected member it breaks my sketch.
How do I declare this global variable
ros::Publisher chatter("chatter", &str_msg);

as a protected variable
protected:
  ros::Publisher chatter("chatter", &str_msg);

without getting this error
expected identifier before string constant

sample .ino
/*
 * rosserial Publisher Example
 * Prints "hello world!"
 */

#include <ros.h>
#include <std_msgs/String.h>

ros::NodeHandle nh;

std_msgs::String str_msg;
ros::Publisher chatter("chatter", &str_msg);

char hello[13] = "hello world!";

void setup()
{
  nh.initNode();
  nh.advertise(chatter);
}

void loop()
{
  str_msg.data = hello;
  chatter.publish( &str_msg );
  nh.spinOnce();
  delay(1000);
}

ROSController class
#include <ros.h>
#include <std_msgs/String.h>

class ROSController {
  protected:
    ros::NodeHandle _nh;
    std_msgs::String str_msg;
//    ros::Publisher chatter("chatter", &str_msg);
    int _throttle;
    bool _is_on = false;
  public:
    void loop();
    ROSController();
    double* getAttitude();
    bool isOn() {
      return this->_is_on;
    }
    int getThrottlePerc() {
      return this->_throttle / ROSController::THR_MAX;
    }

    static const int THR_MAX;
};

const int ROSController::THR_MAX = 100;

ROSController::ROSController() {
  this->_nh.initNode();
//  this->_nh.advertise(chatter);
}

double* ROSController::getAttitude() {
  return new double[3]{0, 0, 0};
}

void ROSController::loop() {
//  str_msg.data = new char[] {"hello"};
//  chatter.publish( str_msg );
  this->_nh.spinOnce();
  delay(1000);
}

I don't understand what you are trying to do there. Some context would be nice - ideally some actual code that demonstrates just what you are trying to do (before and after maybe?)

I added my sample .ino and a little more of the backstory. It's really such a small issue so I was hoping I could keep the question just as simple but I suppose to be thorough you'll have to see the bigger picture.

And where are you trying to move that global variable to?

I've added my ROSController class to the bottom of the question

There's no such thing as a "protected" global variable. Protected variables belong inside classes.

The problem you are having is you are trying to both define and declare a class member variable at the same time. You can't. Instead you need to split it:
protected:
    ros::Publisher chatter;

ROSController::ROSController() : chatter("chatter", &str_msg)
{
    this->_nh.initNode();
//  this->_nh.advertise(chatter);
}

That is, set up the variable as a protected member, then have the constructor call the constructor for you with the right parameters.
(I think that is the right syntax off the top of my head).

Then your Publisher class has no default constructor. Add one.

Hey, that worked! I don't understand what you did on line 4. What is that called? I want to research it and find out more about it.

It's called an initialization list - you can read a little more about it here: http://www.tutorialspoint.com/cplusplus/cpp_constructor_destructor.htm

You can't call the constructor in the class definition. Example:
class foo
  {
  protected:
    String bar ("fubar");
  };

void setup ()
  {
  }  // end of setup

void loop ()
  {
  }  // end of loop

That gives this error:
sketch_sep08b:4: error: expected identifier before string constant
     String bar ("fubar");
                 ^
sketch_sep08b:4: error: expected ',' or '...' before string constant
exit status 1
expected identifier before string constant

Instead declare the class (without the constructor) and call the constructor in the constructor for the parent class, like this:
class foo
  {
  protected:
    String bar;
  public:

    foo () : bar ("fubar") {};  // constructor
  };

void setup ()
  {
  }  // end of setup

void loop ()
  {
  }  // end of loop

authors: ปิยพงษ์ จันทร์ขาว


text:
How to independently control two lights with a single button and a menu system?
I'm stuck and don't know how to get over it.
The problem: i want to use a push button for a menu with 2 screens(frames)
Frame1: if i push the button i want to turn on the light from the room1
        if i press it again i want to turn the light off in the room1
Frame 2: using the same button: i want to turn on the light in the room2
         pressing it again i want to turn the light off in the room2
Now.. the problem i encounter...
if i'm in frame 1 and press the button then the light from room1 will turn on but also the light from the room2 will turn on. and i don't want that.
All i want is to tell somehow to uC that in the frame1 it should turn on only the light from the room1
Please, someone smarter than me ..give me an ideea how can i do that.
i cannot post the code because there are over 3000lines and would be time consuming for you to read it all.
for the buttons i use a counter to see if the state has changed and if so then increment and do what it has to do.
Also i think that the problem is here because i use the same counter in both functions.

int btn1 = 46,starebtn1, stareVechebtn1 = 0, btn2 = 50, starebtn2, stareVechebtn2 = 0;
int btn3 = 42, starebtn3, stareVechebtn3 = 0,btn4 = 40, starebtn4, stareVechebtn4 = 0,btn5 = 44, starebtn5, stareVechebtn5 = 0;
int cntbtn1 = 0, cntbtn2 = 0,cntbtn2_1 = 0, cntbtn3 = 0, cntbtn4 = 0, cntbtn5 = 0;
int soilMoisture = A0;
int buzzer = 3;
boolean frame1 = false, frame2 = false;
int procentajUmiditate(){
  int mSensorValue = analogRead(soilMoisture);
  mSensorValue = map(mSensorValue,0,1023,180,0);
  return mSensorValue;
}
void setup()
{
  Serial.begin(9600);
  dht.begin();
  rtc.begin();
  pinMode(ledVerde,OUTPUT);
  pinMode(buzzer,OUTPUT);
  pinMode(soilMoisture,INPUT_PULLUP);
  pinMode(btn1,INPUT);
  pinMode(btn2,INPUT);
  pinMode(btn3,INPUT);
  pinMode(btn4,INPUT);
  pinMode(btn5,INPUT);
  imagineSistemDomotic();
  delay(3000);
  imagineCasaWifi();
  delay(4000);
  tone(buzzer,1000);
  delay(500);
  noTone(buzzer);
  delay(500);
  digitalWrite(ledVerde,HIGH);
}

void loop()
{

  starebtn1 = digitalRead(btn1);
  starebtn2 = digitalRead(btn2);
  starebtn3 = digitalRead(btn3);
  starebtn4 = digitalRead(btn4);
  starebtn5 = digitalRead(btn5);
  int h = dht.readHumidity();
  int t = dht.readTemperature()-2;
  int f = dht.readTemperature(true);
  temp = t;
  hum = h;
  houR = rtc.getTimeStr();
  dateR = rtc.getDateStr();

//conditii procentaj umiditate si pornire automata irigare
if(procentajUmiditate()<20)
{
  //relayOn
}
else
{
  //relayOff
}

//btn1
 if(starebtn1 != stareVechebtn1)
  {
    if(starebtn1 == HIGH)
    {
      Serial.println(cntbtn1);
      cntbtn1++;
    }
  stareVechebtn1 = starebtn1;
  }//end btn1

//btn2
 if(starebtn2 != stareVechebtn2)
  {
    if(starebtn2 == HIGH)
    {

      cntbtn2 = cntbtn2+1;

    }
    stareVechebtn2 = starebtn2;
  }//endbtn2

//btn3
 if(starebtn3 != stareVechebtn3)
  {
    if(starebtn3 == HIGH)
    {
      cntbtn3 = cntbtn3+1;
    }
    stareVechebtn3 = starebtn3;
  }//endbtn3

//btn4
 if(starebtn4 != stareVechebtn4)
  {
    if(starebtn4 == HIGH)
    {
      cntbtn4 = cntbtn4+1;
    }
    stareVechebtn4 = starebtn4;
  }//endbtn4

//btn5
 if(starebtn5 != stareVechebtn5)
  {
    if(starebtn5 == HIGH)
    {
      cntbtn5 = cntbtn5+1;
    }
    stareVechebtn5 = starebtn5;
  }//endbtn5

//ecran1
     if(cntbtn1 == 1)
    {
     displayInteriorTempHum();
     //u8g.drawStr(23,58,temp.c_str());
    // u8g.drawStr(99,58,hum.c_str());
    }
//ecran2
     if(cntbtn1 == 2)
    {
     displayInteriorLights();
    }

//ecran3
      if(cntbtn1 == 3)
    {
     displayExteriorValues();
    }

     if(cntbtn1 == 4) cntbtn1 = 0;
     if(cntbtn2 == 3) cntbtn2 = 1;
     if(cntbtn2_1 == 3) cntbtn2_1 = 1;
     if(cntbtn3 == 3) cntbtn3 = 1;
} //end loop

void imagineSistemDomotic()
{
  u8g.firstPage();
  do{
    u8g.drawFrame(0,0,128,64);
    u8g.setFont(u8g_font_courB10);
    u8g.drawStr(0,30,"Sistem Domotic");
    }while(u8g.nextPage());
}

void imagineCasaWifi()
{
   u8g.firstPage();
   do{
    u8g.drawFrame(0,0,128,64);
    u8g.drawBitmapP( 0, 1, 16, 64, CasaDomoticaImage2);
     }while(u8g.nextPage());
}

void tempInterior()
{
   u8g.firstPage();
   do{
    u8g.setFont(u8g_font_courB10);
    u8g.drawStr(32,10,"Interior");
    u8g.drawFrame(0,15,128,49);
    u8g.setFont(u8g_font_5x7);
    u8g.drawStr(2,24,dateR.c_str());
    u8g.drawStr(101,24,houR.c_str());
    u8g.setFont(u8g_font_courB10);
    u8g.drawBitmapP( -3, 4, 16, 64, Temp1);
    u8g.drawCircle(40,46,1);
    u8g.drawStr(23,58,"26");
    u8g.setFont(u8g_font_10x20);
    u8g.drawStr(43,58,"C");
    u8g.setFont(u8g_font_courB10);
    u8g.drawBitmapP( 66, 10, 16, 64, UmidLogo);
    u8g.drawStr(99,58,"57");
    u8g.drawStr(117,58,"%");
     }while(u8g.nextPage());
}

void displayExteriorValues()
{
       frame1 = false;
       frame2 = true;
  u8g.firstPage();
      do{
        u8g.setFont(u8g_font_courB10);
        u8g.drawStr(32,10,"Exterior");
        u8g.drawFrame(0,12,128,51);
        u8g.drawLine(64,12,64,62);

       if(cntbtn2 == 1)
       {
        //u8g.drawBitmapP( 15, 30, 16, 64, robinetApaOprita);
        u8g.setFont(u8g_font_5x8);
        u8g.drawStr(78,23,"Irigare");
        u8g.drawStr(78,30,"pornita");
        u8g.drawBitmapP( 72, 8, 16, 64, robinetApaPornita);
        u8g.setPrintPos(15,40);
        u8g.setFont(u8g_font_courB10);
        u8g.print(procentajUmiditate());
        if(procentajUmiditate()<100)
        {
          u8g.setPrintPos(34,40);
          u8g.print("%");
        }
        else
        {
          u8g.setPrintPos(44,40);
          u8g.print("%");
        }

       }

  else{

      //u8g.drawBitmapP( 15, 30, 16, 64, robinetApaOprita);
      u8g.setFont(u8g_font_5x8);
      u8g.drawStr(78,23,"Irigare");
      u8g.drawStr(78,30,"pornita");
      u8g.drawBitmapP( 72, 8, 16, 64, robinetApaPornita);
     // u8g.drawBitmapP( 20, -20, 16, 64, LightOff);
    // valoare buna FanOffLOGO   u8g.drawStr(10,23,"Ventilatie");
   // valoare buna FanOffLOGO    u8g.drawStr(20,30,"oprita");
    //  u8g.drawBitmapP( -15, 24, 16, 64, fanOffLogo);
       u8g.drawStr(10,23,"Umid. Sol");
       u8g.drawBitmapP( 12, -1, 16, 64, UmiditateSol);
       }
       }while(u8g.nextPage());
    cntbtn2 = 0;
}

void displayInteriorLights()
{

   u8g.firstPage();
      do{
      u8g.setFont(u8g_font_courB10);
      u8g.drawStr(32,10,"Interior");
      u8g.drawFrame(0,12,128,51);
      u8g.drawLine(64,12,64,62);
      u8g.setFont(u8g_font_5x8);

      if(cntbtn2 == 1)
      {
      u8g.drawStr(73,23,"Dormitor");
      u8g.drawStr(75,60,"L.aprinsa");
      u8g.drawBitmapP( 78, 7, 16, 64, LightOn);
      }
      else if(cntbtn2 == 2)
      {
      u8g.drawStr(73,23,"Dormitor");
      u8g.drawStr(75,60,"L.stinsa");
      u8g.drawBitmapP( 78, 7, 16, 64, LightOff);
      }
      else{
      u8g.drawStr(73,23,"Dormitor");
      u8g.drawStr(75,60,"L.stinsa");
      u8g.drawBitmapP( 78, 7, 16, 64, LightOff);
      }

      if(cntbtn3 == 1)
      {
      u8g.drawStr(10,23,"Sufragerie");
      u8g.drawStr(15,60,"L.aprinsa");
      u8g.drawBitmapP( 20, 8, 16, 64, LightOn);
      }
      else if(cntbtn3 == 2)
      {
      u8g.drawStr(10,23,"Sufragerie");
      u8g.drawStr(15,60,"L.stinsa");
      u8g.drawBitmapP( 20, 8, 16, 64, LightOff);
      }
    //else if(digitalRead(relay)

    else{
      u8g.drawStr(10,23,"Sufragerie");
      u8g.drawStr(15,60,"L.stinsa");
      u8g.drawBitmapP( 20, 8, 16, 64, LightOff);
    }
      }while(u8g.nextPage());

}

void displayInteriorTempHum()
{
      u8g.firstPage();
      do{
      u8g.setFont(u8g_font_courB10);
      u8g.drawStr(32,10,"Interior");
      u8g.drawFrame(0,15,128,49);
      u8g.setFont(u8g_font_5x7);
      u8g.drawStr(2,24,dateR.c_str());
      u8g.drawStr(101,24,houR.c_str());
      u8g.setFont(u8g_font_courB10);
      u8g.drawBitmapP( -3, 4, 16, 64, Temp1);
      u8g.drawCircle(40,46,1);
      u8g.drawStr(23,58,temp.c_str());
      u8g.setFont(u8g_font_10x20);
      u8g.drawStr(43,58,"C");
      u8g.setFont(u8g_font_courB10);
      u8g.drawBitmapP( 66, 10, 16, 64, UmidLogo);
      u8g.drawStr(99,58,hum.c_str());
      u8g.drawStr(117,58,"%");
      digitalWrite(ledVerde,LOW);
        }while(u8g.nextPage());
}

Sorry, but  your question is very unclear. Can you edit your post using correct prepositions? Like: "IN the kitchen", "IN the bedroom". Also, "SWITCH ON the light bulb". Remember, saying "switching light FROM x room" means: "Switching light by pressing button which is located IN room x".

whenever the button is pressed, check the room number that it is operating on, then act accordingly

Difficult to advise without more clear information but here's a couple of ideas to play around with (currently typing on my phone, will edit later).
If using a physical menu and buttons then you need some way to track location. You could try adding proximity sensors to check physical location/proximity to the light source and let that be the deciding variable for which bulb gets activated. You could use a "universal remote" approach, using separate arduinos (per light) with IR receivers.
If using an app menu, like on a phone, try declaring a variable "room" and have the button pass the frame name or ID number based on the frame ("bedroom" or "kitchen", "1" or "2" etc) as that variable via your communication line to the arduino. On the arduino side, declare the same variable and process the received data from the app i.e. String room = your-room-ID. Ensure you have separate pinout declarations for each bulb you want to control i.e. #define kitchen 14 # define livingroom 15... setPin(output, kitchen), setPin(output, livingroom) then modify your bulb activation line to be pinout(room, HIGH);

Reading your answer i understand mostly that i was not so clear in my post. And i am agree with you on that. Now.. imagine that i have an glcd which is divided by 2. On the left is room 1 light and on the right is ventilation for room1.  That in the Frame 1. In the Frame 2(btw i scroll into the frames using another button) so, in Frame 2 the image is also divided by 2. On the left light for room2 and on the right is the temp for room2. Now, besides the button that i use for switching the frames, i have another 2 that i want to use for "current" frame that i am in.

So.. if i press the button wich is positioned under the left side lf the screen. I could turn on or off the light in the room 1. But the problem is that the light will be turned on even in the room 2

My app code notes still apply, you are controlling the glcd with the same arduino? If so then just add an extra line of code to set your room variable when the frame is changed and use the rest of the pin coding as I described. This is all assuming there are no errors in your current coding that are making this result happen, without your sketch we will never be able to tell.

here is a part of it

It's really very simple, I think...  If I understood properly...
global frame, lightRoom1, lightRoom2

function changeFrame ( ) {

// if frame == 1, change it to 2

    if ( frame == 1 ) {
        <commands to refresh display>;
        frame = 2;
    } else {
        <commands to refresh display>
        frame = 1;
    }

}

function switchLight ( ) {

// roomno = frameno.
// if light on, switch off; if off, switch on.

    if ( frame == 1 ) {

        if ( lightRoom1 == false ) {
            <code to switch light on >;
            lightRoom1 == true;
        } else {
            <code to switch light off >;
            lightRoom1 == false;
        }

    }

    if ( frame == 2 ) {

        // same as above but for room 2.

    }

}

if ( digitalRead ( framePin ) == LOW ) {
    changeFrame ( );
}

if ( digitalRead ( lightPin ) == LOW ) {
    switchLight ( );
}

The code you show is indeed too long. However, a cursory look seems to
indicate that you are not using any debouncing library. This is then the
first thing you should do. There are probably many options. I will
suggest Bounce2 which, in addition to debouncing, handles the edge
detection. Then you have the fell() method that tells you whether the
input signal just fell since the last time it was tested, which is a way
to detect the button press.
Then, within loop(), you would add something like this:
if (mainButton.update() && mainButton.fell()) {

    // Find the pin that controls the appropriate light.
    uint8_t lightPin;
    if (currentFrame == FRAME1) {
        lightPin = PIN_LIGHT_ROOM_1;
    } else {  // FRAME2
        lightPin = PIN_LIGHT_ROOM_2;
    }

    // Toggle the light.
    if (digitalRead(lightPin) == HIGH) {
        digitalWrite(lightPin, LOW);
    } else {
        digitalWrite(lightPin, HIGH);
    }
}

The assumptions I am making should be pretty obvious:

currentFrame is a variable updated by your menu system. Its value
can only be one of the constants FRAME_1 or FRAME_2
PIN_LIGHT_ROOM_1 and PIN_LIGHT_ROOM_2 are constants holding the
pin numbers which control the corresponding lights.