Temperature sensor utilization to a LED on - arduino-uno

I work on a program which should light a LED on when the temperature is below 30°C. I am getting an error while compiling it. Could you guys please look into it? What am I doing wrong?
/*
* Code d'exemple pour le capteur LM35DZ (0°C ~ +110°C).
*/
const int led_rouge = 3; //définition de la broche 3 de la carte étant la LED
int valeur_brute;
// Fonction setup(), appelée au démarrage de la carte Arduino
void setup() {
// Initialise la communication avec le PC
Serial.begin(9600);
//initialisation de la broche 3 comme étant une sortie
pinMode(led_rouge, OUTPUT);
}
// Fonction loop(), appelée continuellement en boucle tant que la carte Arduino est alimentée
void loop() {
// Mesure la tension sur la broche A1
int valeur_brute = analogRead(A1);
// Transforme la mesure (nombre entier) en température via un produit en croix
float temperature_celcius = valeur_brute * (5.0 / 1023.0 * 100.0);
// Envoi la mesure au PC pour affichage et attends 250ms
Serial.println(temperature_celcius);
delay(250);
//Condition de fonctionnement de la LED
if( valeur_brute < 100/110 ) //si température inférieur à 30°C
{
digitalWrite(led_rouge, HIGH);
}
if ( valeur_brute > 100/110 ){
digitalWrite(led_rouge, LOW);
}
}
This is the error I get with the previous code
F:\Alexis\Temperature\Temperature - LED.ino: In function 'void setup()':
F:\Alexis\Temperature\Temperature - LED.ino:6:6: error: redefinition of 'void setup()'
void setup() {
^
F:\Alexis\Temperature\Temperature.ino:8:6: note: 'void setup()' previously defined here
void setup() {
^
F:\Alexis\Temperature\Temperature - LED.ino: In function 'void loop()':
F:\Alexis\Temperature\Temperature - LED.ino:13:6: error: redefinition of 'void loop()'
void loop() {
^
F:\Alexis\Temperature\Temperature.ino:20:6: note: 'void loop()' previously defined here
void loop() {
^
exit status 1
Erreur de compilation pour la carte Arduino/Genuino Uno

You are redefining a CONST variable in your setup
int led_rouge = LOW;.
A const variable cannot be overwritten. Just delete the line in the setup. The following Sketch is working fine for me:
const int led_rouge = 3;
int valeur_brute;
void setup() {
Serial.begin(9600);
pinMode(led_rouge, OUTPUT);
}
void loop() {
int valeur_brute = analogRead(A1);
float temperature_celcius = valeur_brute * (5.0 / 1023.0 * 100.0);
Serial.println(temperature_celcius);
delay(250);
if( temperature_celcius < 100/110 ){
digitalWrite(led_rouge, HIGH);
}
if ( temperature_celcius > 100/110 ){
digitalWrite(led_rouge, LOW);
}
}

Related

LVGL Compile error “dram0.bss’ will not fit in region `dram0_0_seg’” with ILI9488 & ESP32 on Arduino Core

I constantly get this error, no matter what I'm doing... I have an ILI9488 with 4-wire SPI and a GT911 capacitive Touch driver on an ESP32 (2MB, no PSRAM, arduino core).
this is my main.ino-file:
#include <lvgl.h>
#include <TFT_eSPI.h>
#include <Wire.h>
#include "Goodix.h"
#define INT_PIN 26
#define RST_PIN 15
#define SDA_PIN 22
#define SCL_PIN 16
Goodix touch = Goodix();
#define DISPLAY_BUF_SIZE 480 * 10
static uint16_t display_widht = 480;
static uint16_t display_height = 320;
TFT_eSPI tft = TFT_eSPI(); /* TFT instance */
bool touched = false;
GTPoint touchDat;
static lv_disp_draw_buf_t draw_buf;
static lv_color_t buf[ DISPLAY_BUF_SIZE];
lv_disp_drv_t disp_drv; //display driver
lv_indev_drv_t touch_drv; //touchpad driver
void my_disp_flush( lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *color_p ){
uint32_t w = ( area->x2 - area->x1 + 1 );
uint32_t h = ( area->y2 - area->y1 + 1 );
tft.startWrite();
tft.setAddrWindow( area->x1, area->y1, w, h );
tft.pushColors( ( uint16_t * )&color_p->full, w * h, true );
tft.endWrite();
lv_disp_flush_ready( disp );
}
void handleTouch(int8_t contacts, GTPoint* points) {
Serial.printf("Contacts: %d\n", contacts);
if(contacts > 0) touched = true;
else touched = false;
for (uint8_t i = 0; i < contacts; i++) {
touchDat = points[0];
Serial.printf("C%d: %d %d \n", points[i].trackId, points[i].x, points[i].y);
}
}
/*Read the touchpad*/
void my_touchpad_read( lv_indev_drv_t * touch_drv, lv_indev_data_t * data ){
if( !touched ) //kein Touch
{
data->state = LV_INDEV_STATE_REL;
}
else //touch!
{
data->state = LV_INDEV_STATE_PR;
/*Set the coordinates*/
data->point.x = touchDat.x;
data->point.y = touchDat.y;
}
}
void i2cInit(){
Wire.setPins(SDA_PIN, SCL_PIN);
Wire.setClock(400000);
Wire.begin();
delay(100);
}
void touchInit() {
touch.setHandler(handleTouch);
touch.setRes(display_widht, display_height);
touch.setRotation(3);
touch.begin(INT_PIN, RST_PIN, GOODIX_I2C_ADDR_28);
Serial.print("Check ACK on addr request on 0x");
Serial.print(touch.i2cAddr, HEX);
Wire.beginTransmission(touch.i2cAddr);
if (!Wire.endTransmission()) {
Serial.println(": SUCCESS");
} else {
Serial.print(": ERROR!");
}
}
void tftInit(){
tft.begin();
tft.setRotation(3);
lv_disp_draw_buf_init( &draw_buf, buf, NULL, DISPLAY_BUF_SIZE ); //init draw Buffer
/*Initialize the display*/
static lv_disp_drv_t disp_drv;
lv_disp_drv_init( &disp_drv );
/*Change the following line to your display resolution*/
disp_drv.hor_res = display_widht;
disp_drv.ver_res = display_height;
disp_drv.flush_cb = my_disp_flush;
disp_drv.draw_buf = &draw_buf;
lv_disp_drv_register( &disp_drv );
/*Initialize the input device driver*/
static lv_indev_drv_t touch_drv;
lv_indev_drv_init( &touch_drv );
touch_drv.type = LV_INDEV_TYPE_POINTER;
touch_drv.read_cb = my_touchpad_read;
lv_indev_drv_register( &touch_drv );
//create simple label
lv_obj_t *label = lv_label_create( lv_scr_act() );
lv_label_set_text( label, "Hello World!!" );
lv_obj_align( label, LV_ALIGN_CENTER, 0, 0 );
}
void setup() {
Serial.begin(115200); /* prepare for possible serial debug */
i2cInit();
touchInit(); //initialize touch
lv_init();
}
void loop() {
touch.loop();
lv_task_handler(); /* let the GUI do its work */
delay(5);
}
these are my main.ino and lv_config.h-files:
https://gist.github.com/kokospalme/a65448c1d10704066b9c6d2350c84a6d
even if I change LV_MEM_SIZE to something small like 1 or 10, I get the error, that " region `dram0_0_seg' overflowed by 22272 bytes". What am I doing wrong?

Attiny85 with ArduinoUno for I2c comm

I am working on attiny85 for I2C communication. I have gone through different libraries already like Wire.h, TinyWire.h, tinyWireM.h, tinyWireS.h.
In the start I want to send some byte of data through I2C comm and tried to scope the pin with oscilloscope but its not giving me the appropriate results. Looking on the internet about different ways to make attiny85 work with I2c is really heartless and I could not achieve the task. Finally, I tried to make attiny85 as master and arduino Uno as slave as it was spare in my box.
I tried to make attiny85 as master and send data to arduino and looks the output on serial monitor but its showing zero.
For the reference, the master and slave codes are attached and my task is just simple to check on serial.
Attiny85 as Master
#include <TinyWireM.h>
void setup()
{
TinyWireM.begin();
}
void loop()
{
TinyWireM.begin();
TinyWireM.beginTransmission(0x08);
TinyWireM.send(0x99);
int Byte1 = TinyWireM.endTransmission();
delay(1000);
}
Arduino as Slave
#include <Wire.h>
const byte add = 0x08;
int byte1;
void setup()
{
Wire.begin(add);
Wire.onReceive(receiveEvent);
Serial.begin(9600);
}
void loop()
{
Serial.println ("Data receiving");
Serial.println(byte1);
delay(1000);
}
void receiveEvent(int bytes)
{
byte1 = Wire.read();
}
But I am not able to get the output on serial monitor of arduino.
What am i doing wrong here?
I have used Atiny85 as a slave using TinyWireS lib (https://github.com/nadavmatalon/TinyWireS) some time back and it worked fine.
Below were the pin configurations
ATtiny85 pin 5 with Arduino Uno A4 and
ATtiny85 pin 7 with Arduino Uno A5
Below are my codes
Atiny.
#include "TinyWireS.h"
const byte SLAVE_ADDR = 100;
const byte NUM_BYTES = 4;
volatile byte data = { 0, 1, 2, 3 };
void setup() {
TinyWireS.begin(SLAVE_ADDR);
TinyWireS.onRequest(requestISR);
}
void loop() {}
void requestISR() {
for (byte i=0; i<NUM_BYTES; i++) {
TinyWireS.write(data[i]);
data[i] += 1;
}
}
Uno.
#include <Wire.h>
const byte SLAVE_ADDR = 100;
const byte NUM_BYTES = 4;
byte data[NUM_BYTES] = { 0 };
byte bytesReceived = 0;
unsigned long timeNow = millis();
void setup() {
Serial.begin(9600);
Wire.begin();
Serial.print(F("\n\nSerial is Open\n\n"));
}
void loop() {
if (millis() - timeNow >= 750) { // trigger every 750mS
Wire.requestFrom(SLAVE_ADDR, NUM_BYTES); // request bytes from slave
bytesReceived = Wire.available(); // count how many bytes received
if (bytesReceived == NUM_BYTES) { // if received correct number of bytes...
for (byte i=0; i<NUM_BYTES; i++) data[i] = Wire.read(); // read and store each byte
printData(); // print the received data
} else { // if received wrong number of bytes...
Serial.print(F("\nRequested ")); // print message with how many bytes received
Serial.print(NUM_BYTES);
Serial.print(F(" bytes, but got "));
Serial.print(bytesReceived);
Serial.print(F(" bytes\n"));
}
timeNow = millis(); // mark preset time for next trigger
}
}
void printData() {
Serial.print(F("\n"));
for (byte i=0; i<NUM_BYTES; i++) {
Serial.print(F("Byte["));
Serial.print(i);
Serial.print(F("]: "));
Serial.print(data[i]);
Serial.print(F("\t"));
}
Serial.print(F("\n"));
}

Whats the purpose of "num" in arduinoWebSockets?

Whats the purpose of num in webSocket.sendTXT(num, "Connected"); or at any other place its used in the code, what function does it serve? Because it doesn't ever get defined as anything anywhere, but it is required to
be passed as a function argument for it to work.
In void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) it's set as a function parameter.
Links2004/arduinoWebSockets Library
/*
* WebSocketServer_LEDcontrol.ino
*
* Created on: 26.11.2015
*
*/
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WebSocketsServer.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <Hash.h>
#define LED_RED 15
#define LED_GREEN 12
#define LED_BLUE 13
#define USE_SERIAL Serial
ESP8266WiFiMulti WiFiMulti;
ESP8266WebServer server = ESP8266WebServer(80);
WebSocketsServer webSocket = WebSocketsServer(81);
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {
switch(type) {
case WStype_DISCONNECTED:
USE_SERIAL.printf("[%u] Disconnected!\n", num);
break;
case WStype_CONNECTED: {
IPAddress ip = webSocket.remoteIP(num);
USE_SERIAL.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);
// send message to client
webSocket.sendTXT(num, "Connected");
}
break;
case WStype_TEXT:
USE_SERIAL.printf("[%u] get Text: %s\n", num, payload);
if(payload[0] == '#') {
// we get RGB data
// decode rgb data
uint32_t rgb = (uint32_t) strtol((const char *) &payload[1], NULL, 16);
analogWrite(LED_RED, ((rgb >> 16) & 0xFF));
analogWrite(LED_GREEN, ((rgb >> 8) & 0xFF));
analogWrite(LED_BLUE, ((rgb >> 0) & 0xFF));
}
break;
}
}
void setup() {
//USE_SERIAL.begin(921600);
USE_SERIAL.begin(115200);
//USE_SERIAL.setDebugOutput(true);
USE_SERIAL.println();
USE_SERIAL.println();
USE_SERIAL.println();
for(uint8_t t = 4; t > 0; t--) {
USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
USE_SERIAL.flush();
delay(1000);
}
pinMode(LED_RED, OUTPUT);
pinMode(LED_GREEN, OUTPUT);
pinMode(LED_BLUE, OUTPUT);
digitalWrite(LED_RED, 1);
digitalWrite(LED_GREEN, 1);
digitalWrite(LED_BLUE, 1);
WiFiMulti.addAP("SSID", "passpasspass");
while(WiFiMulti.run() != WL_CONNECTED) {
delay(100);
}
// start webSocket server
webSocket.begin();
webSocket.onEvent(webSocketEvent);
if(MDNS.begin("esp8266")) {
USE_SERIAL.println("MDNS responder started");
}
// handle index
server.on("/", []() {
// send index.html
server.send(200, "text/html", "<html><head><script>var connection = new WebSocket('ws://'+location.hostname+':81/', ['arduino']);connection.onopen = function () { connection.send('Connect ' + new Date()); }; connection.onerror = function (error) { console.log('WebSocket Error ', error);};connection.onmessage = function (e) { console.log('Server: ', e.data);};function sendRGB() { var r = parseInt(document.getElementById('r').value).toString(16); var g = parseInt(document.getElementById('g').value).toString(16); var b = parseInt(document.getElementById('b').value).toString(16); if(r.length < 2) { r = '0' + r; } if(g.length < 2) { g = '0' + g; } if(b.length < 2) { b = '0' + b; } var rgb = '#'+r+g+b; console.log('RGB: ' + rgb); connection.send(rgb); }</script></head><body>LED Control:<br/><br/>R: <input id=\"r\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" oninput=\"sendRGB();\" /><br/>G: <input id=\"g\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" oninput=\"sendRGB();\" /><br/>B: <input id=\"b\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" oninput=\"sendRGB();\" /><br/></body></html>");
});
server.begin();
// Add service to MDNS
MDNS.addService("http", "tcp", 80);
MDNS.addService("ws", "tcp", 81);
digitalWrite(LED_RED, 0);
digitalWrite(LED_GREEN, 0);
digitalWrite(LED_BLUE, 0);
}
void loop() {
webSocket.loop();
server.handleClient();
}
Looking at the library's source code, it reveals that it's a client id, so you can differentiate between multiple clients, that are connected at the same time.
/*
* send text data to client
* #param num uint8_t client id
* #param payload uint8_t *
* #param length size_t
* #param headerToPayload bool (see sendFrame for more details)
* #return true if ok
*/
bool WebSocketsServer::sendTXT(uint8_t num, uint8_t * payload, size_t length, bool headerToPayload) {
if(num >= WEBSOCKETS_SERVER_CLIENT_MAX) {
return false;
}
if(length == 0) {
length = strlen((const char *) payload);
}
WSclient_t * client = &_clients[num];
if(clientIsConnected(client)) {
return sendFrame(client, WSop_text, payload, length, false, true, headerToPayload);
}
return false;
}

How i write multiple float data to Arduino from Rpi as master via i2c?

I read many post how Rpi receives float data via Arduino via i2c, with Rpi as master.
But i need write floats values to arduino and i don't found any example. I want to use python smbus.
Any one have a example?
Thanks a lot!
After many tests, i can exchange multiple data between arduino as slave and Raspberry pi3 as master.
Arduino code:
#include <Wire.h>
byte data[12];
int command;
typedef struct processData{
float temp1;
float temp2;
float temp3;
float temp4;
float vazao_quente;
float vazao_fria;
byte pump_speed;
//bool pump_status;
byte bstatus;
//bool heater_status;
byte chksum;
};
typedef union I2C_Send{
processData data;
byte I2C_packet[sizeof(processData)];
};
I2C_Send send_info;
void parseValues(byte data[]){
union float_tag{
byte b[4];
float fval;
}ft;
ft.b[0] =data[1];
ft.b[1] = data[2];
ft.b[2] = data[3];
ft.b[3] = data[4];
Serial.println(ft.fval);
}
void setup()
{
Wire.begin(12); // join i2c bus with address #4
Wire.onReceive(receiveEvent); // register event
Wire.onRequest(requestEvent);
Serial.begin(9600); // start serial for output
setrnddata();
}
void loop()
{
delay(100);
}
// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany)
{
command = Wire.read();
if (command==1){
int i=0;
while(1 <= Wire.available()) // loop through all but the last
{
data[i] = Wire.read(); // receive byte as a character
i = i+1;
}
parseValues(data);
}
}
void requestEvent()
{
if(command==2){
Wire.write(send_info.I2C_packet,sizeof(processData));
}
}
Raspberry code:
from datetime import datetime
from datetime import timedelta
from smbus import SMBus
import struct
start_time = datetime.now()
def millis():
dt = datetime.now()-start_time
ms = (dt.days*24*60*60 + dt.seconds)*1000+dt.microseconds / 1000.0
return ms
#inicia escravo i2c
bus = SMBus(1)
arduinoAddress = 12
#interval request
interval = 150
temperatura = 10.2
vazao = 5.3
command = 20
teste = 30
if __name__ == '__main__':
prevmillis = millis()
while True:
currentmillis = millis()
if(currentmillis - prevmillis > interval):
#write
bytescommand = struct.pack('=2fbb',temperatura,vazao,command,teste)
bus.write_block_data(arduinoAddress,1,list(bytescommand))
print(list(bytescommand))
#request
block = bus.read_i2c_block_data(arduinoAddress,2,27)
output = struct.unpack('6f3b',bytes(block))
print(output)
print(datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
prevmillis = currentmillis
I hope helps someone!
Thanks!

Why can't redraw SecondApplet with processing?

I am working with processing 3 and I am actually trying to work with 2 windows.
I would like redraw the second window but redraw do nothing (In final project data incoming from serial port will make the redraw). I don't know why.
Here is my code :
/*
* 17.09.16 : Logan Gallois
* future imporvement :
* Windows print graph of PWMs values from RGB LED
* Add autoDetect position to move windows at the good location
*/
import processing.serial.*;
Serial myPort;
SecondApplet sa;
int[] numbers = new int[600];
boolean flag = false;
float var1;
float var2;
float var3;
float var4;
void setup() {
size(1024, 576); //Affiche en plein écran
surface.setResizable(false);
noStroke();
println(Serial.list()); /* Verifier dans la liste ou se trouve l'arduino */
/* Puis changer en dessous la valeur en fonction */
/* En general 0 pour windows et 1 pour un mac */
String os=System.getProperty("os.name"); /* Detection automatique de l'OS */
if(os != "Mac OS X") {
if(Serial.list().length > 0) {
myPort = new Serial(this, Serial.list()[0], 115200);
}
} else {
if(Serial.list().length > 1) { /* Module BLE en position 0 */
myPort = new Serial(this, Serial.list()[1], 115200);
}
}
//Important : se câler sur la valeur en baud du prog Arduino
myPort.bufferUntil('\n');
String[] args = {"TwoFrameTest"};
sa = new SecondApplet();
PApplet.runSketch(args, sa);
delay(100);
}
void draw() {
if(!flag) {
surface.setLocation(displayWidth/2-width/2-400,displayHeight/2-height/2);
sa.frame.setTitle("Monitoring RGB Values");
flag = true;
}
background(color(int(var1), int(var2), int(var3)));
//sa.background(0, 255, 0);
/*for(int i = 0 ;i<=width/10;i++){
sa.stroke(200);
sa.line((-frameCount%10)+i*10,0,(-frameCount%10)+i*10,height);
sa.line(0,i*10,width,i*10);
}
sa.noFill();
sa.stroke(0);
sa.beginShape();
for(int i = 0; i<numbers.length;i++){
sa.vertex(i,350-numbers[i]);
}
sa.endShape();
for(int i = 1; i<numbers.length;i++){
numbers[i-1] = numbers[i];
}
numbers[numbers.length-1]=mouseY;*/
}
void mouseClicked() {
print("clicked");
sa.background(0, 0, 255);
sa.fill(100);
sa.redraw(); //This line do not redraw my 'sa' window
background(0, 0, 255);
redraw();
}
void serialEvent (Serial myPort) {
String inString = myPort.readStringUntil('\n');
//println(inString);
if (inString != null) {
inString = trim(inString);
int inputs[] = int(split(inString,',')); // on élude les virgules
// on affecte nos 4 valeurs
if(inputs.length == 4) {
var1 = inputs[0];
var2 = inputs[1];
var3 = inputs[2];
var4 = inputs[3];
// On ré-échelonne la valeur analogique en valeur RGB
var1 = map(var1, 0, 1023, 0, 255);
var2 = map(var2, 0, 1023, 0, 255);
var3 = map(var3, 0, 1023, 0, 255);
var4 = map(var3, 0, 1023, 0, 255);
print(int(var1));
print(" ,");
print(int(var2));
print(" ,");
print(int(var3));
print(" ,");
println(var4);
}
}
}
public class SecondApplet extends PApplet {
public void settings() {
size(600, 600);
noLoop(); //I tried with and without that
}
public void draw() {
}
public void mouseClicked() {
print("clicked2");
background(0, 255, 0);
redraw(); //This line works great
}
}
Any Ideas ?
When posting, please try to narrow your problem down to an MCVE. That means taking out all the Serial stuff and just using basic mouse events.
Your second sketch's draw() function is empty. What do you expect calling redraw() to actually do?
Here's an example MCVE:
SecondApplet sa;
void setup() {
size(500, 500); //Affiche en plein écran
String[] args = {"TwoFrameTest"};
sa = new SecondApplet();
PApplet.runSketch(args, sa);
delay(100);
}
void draw() {
background(255, 0, 0);
}
void mouseClicked() {
sa.redraw();
}
public class SecondApplet extends PApplet {
public void settings() {
size(100, 100);
noLoop();
}
public void draw() {
background(0);
ellipse(random(width), random(height), 25, 25);
}
public void mouseClicked() {
redraw();
}
}
This MCVE works perfectly, and correctly triggers the second sketch's draw() function from both the first and second sketch windows.
I'd recommend working from this MCVE. If you still can't get it working, feel free to post a follow-up question, preferably without the serial stuff (which makes your sketch impossible to run since we don't have access to your hardware). Good luck.

Resources