adafruit 아닌 GPIO 로 DHT11

import RPi.GPIO as GPIO
import time

def bin2dec(string_num): # define a function to convert a binary number to a decimal.
return str(int(string_num, 2)) # return the string representing the integer value of the string passed to this function in base 2 (binary)

data = [] # define a data array

GPIO.setmode(GPIO.BCM) # use the Broadcom numbers instead of the WiringPi numbers

GPIO.setup(4,GPIO.OUT) # Set it as an output so that we can:
GPIO.output(4,GPIO.HIGH) # write a 1
time.sleep(0.025) # for 25 ms
GPIO.output(4,GPIO.LOW) # then write a 0
time.sleep(0.02) # for 20 ms.

I assume that the preceding sequence is the method to get the DHT sensor to respond with the current data.

GPIO.setup(4, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Change the pin to read mode, with a pullup resistor

for i in range(0,500): # 501 times
data.append(GPIO.input(4)) # read a bit from the GPIO, as fast as possible (no wait)

bit_count = 0
tmp = 0
count = 0
HumidityBit = “”
TemperatureBit = “”
crc = “”

try: # do this unless there’s an error. If there’s an error jump to “Except:”
while data[count] == 1: # as long as you read a 1
tmp = 1
count = count + 1 # count how many 1s have been read

for i in range(0, 32): # do this 33 times
    bit_count = 0 # reset the bit count each time

    while data[count] == 0: # as long as a 0 is read
        tmp = 1
        count = count + 1 # move on to the next bit

    while data[count] == 1: # as long as a 1 is read
        bit_count = bit_count + 1 # count how many 1s in a row
        count = count + 1 # move on to the next bit

    if bit_count > 3: # if there were mote than 3 * 1-bits in a row
        if i>=0 and i<8: # if we're in the first byte
            HumidityBit = HumidityBit + "1" # append a 1 to the humidity bitstring
        if i>=16 and i<24: # if we're in the 3rd byte
            TemperatureBit = TemperatureBit + "1" # add a 1 to the temperature bitstring
    else: # if there weren't at least 3 * 1-bits
        if i>=0 and i<8: # if we're in the first byte
            HumidityBit = HumidityBit + "0" # append a 0 to the humidity bitstring
        if i>=16 and i<24: # if we're in the 3rd byte
            TemperatureBit = TemperatureBit + "0" # append a 0 to the temperature bitstring

except: # if there was an error in the “try:” block
print “ERR_RANGE” # report it
exit(0) # end the program

try: # do this unless there’s an error. If there’s an error jump to “Except:”
for i in range(0, 8): # do this 9 times
bit_count = 0 # reset the bit counter

    while data[count] == 0: # as long as a 0 was read
        tmp = 1
        count = count + 1 # move on to the next bit

    while data[count] == 1: # as long as a 1 was read
        bit_count = bit_count + 1 # count how many 1s
        count = count + 1 # move on to the next bit

    if bit_count > 3: # if there were at least 3 * 1-bits
        crc = crc + "1" # add a 1 to the crc (Cyclic redundancy check) bitstring
    else: # if there were less than 3* 1-bits
        crc = crc + "0" # add a 0 to the crc bitstring

except: # if the “try:” block failed
print “ERR_RANGE” # report it
exit(0) # end program

Humidity = bin2dec(HumidityBit) # convert the binary bitstring to a decimal variable for humidity
Temperature = bin2dec(TemperatureBit) # convert the binary bitstring to a decimal variable for temperature

if int(Humidity) + int(Temperature) – int(bin2dec(crc)) == 0: # test whether the CRC indicates that the reading was good
print Humidity # duh
print Temperature # duh
else: # if the CRC check was bad
print “ERR_CRC” # report it

looks like there should be an “exit (0)” here that’s missing. The program ends either way though. Usually the exit value indicates whether the program completed successfully.

광고

[예제] 파이로 습도 센서 사용

사용 센서 : DHT11 MODULE

Power: DC 3~5V

Pins: G (GND) – D (Data) – V (VCC)

Humidity Measurement: 20~80% humidity reading with 5% accuracy

Temperature Measurement: 0~50°C temperature reading with ±2°C accuracy

Should not measure more than once per second

How to Set Up the DHT11 Humidity Sensor on the Raspberry Pi

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

while True:
humidity, temperature = Adafruit_DHT.read_retry(11, 4)

print ('Temp: {0:0.1f} C  Humidity: {1:0.1f} %'.format(temperature, humidity))

Adafruit_DHT ; invalid module error

-> Adafruit_Python_DHT 로 수정. -> sudo apt-get upgrade

네트워크 용어 정리 (스위치, 라우터)

이더넷 : 가장 대표적인 버스 구조 방식의 근거리통신망(LAN)

CSMA/CD(carrier sense multiple access with collision detection) 방식을 사용. 데이터를 보내려는 컴퓨터가 먼저 통신망이 사용 중인지 아닌지 검사한 후에 비어 있을 때 데이터를 보낸다. 통신망이 사용 중이면 일정시간을 기다린 후 다시 검사한다. 통신망이 사용 중인지는 전기적인 신호로 확인할 수 있다.

[네이버 지식백과] 이더넷 [Ethernet] (두산백과)

스위치 :

네트워크 스위치(network switch)는 처리 가능한 패킷의 숫자가 큰 것으로, 네트워크 단위 들을 연결하는 통신 장비로서 소규모 통신을 위한 허브보다 전송 속도가 개선된 것이다. 간단히 스위치라고 부르는 경우가 많으며, MAC 브리지[1]스위칭 허브(switching hub), 포트 스위칭 허브(port switching hub)라고도 한다.

[출처] [네트워크] 스위치와 라우터의 차이|작성자 ykycome00

네트워크 상에서 한 점이 다른 둘 이상의 점에 연결되는 일은 흔하게 발생한다. 이때 그 점은 들어온 입력을 여러 방향 (즉, ‘선’)으로 보낼 수 있고, 이처럼 경로를 결정한다는 의미에서 스위치라고 이야기한다. 마치 교차로에서 길을 선택하는 것과 같다고 생각하면 된다. 우리가 컴퓨터 네트워크에서 일반적으로 말하는 스위치는 OSI 모델상 제2계층인 “데이터링크 계층”에 해당하는 Ethernet 상의 데이터들의 경로를 결정한다고 해서 Layer 2 (또는 L2) 스위치라고 부른다. “스위치와 허브의 차이는..” 식으로 외우고 있는 분들도 많을 것이다. 그것도 나쁘지 않지만, 경로의 결정을 하는 것이 스위치라고 이해하면 “ATM 스위치”, “패킷 스위칭” 이런 표현들이 무엇을 뜻하는 것인지 보다 쉽게 감이 올 것이다.

원문보기: 
http://www.inven.co.kr/webzine/news/?news=168090#csidxfac5fbdb0a6e6f0a99206d212fc985a 


라우터 :

라우터(router[a]문화어: 경로기) 혹은 라우팅 기능을 갖는 공유기는 패킷의 위치를 추출하여, 그 위치에 대한 최적의 경로를 지정하며, 이 경로를 따라 데이터 패킷을 다음 장치로 전향시키는 장치이다. 이때 최적의 경로는 일반적으로는 가장 빠르게 통신이 가능한 경로이므로, 이것이 최단 거리 일수도 있지만, 돌아가는 경로라도 고속의 전송로를 통하여 전달이 되는 경로가 될 수 있다. 간단히 말해 서로 다른 네트워크 간에 중계 역할을 해준다.

[출처] [네트워크] 스위치와 라우터의 차이|작성자 ykycome00

라우팅 :

라우팅(영어: routing)은 어떤 네트워크 안에서 통신 데이터를 보낼 경로를 선택하는 과정이다. 라우팅은 전화 통신망, 전자 정보 통신망(인터넷 같은) 그리고 교통망 등 여러 종류의 네트워크에서 사용된다. 이 글은 패킷 스위칭 기술을 이용한 컴퓨터 네트워크에서의 라우팅에 대해 주로 기술한다.

[출처] [네트워크] 스위치와 라우터의 차이|작성자 ykycome00

– 스위치 라우터 차이점

원래는 Layer 2에서 data를 교환해주는것을 network switch라고 부르는데,
Layer 2뿐만이 아니라, 추가적으로 Layer 3의 데이터도 처리하는애들은
Layer 3 switch나 Multi-Layer switch라고 부름.

그리고, 이 Layer 3 switch들은 관행상, router라고 불려왔다고 함.
따라서, Layer-3 switches가 router의 정의라고 할수 있음.

식별자가 MAC주소인지 IP주소인지의 차이

[출처] [네트워크] 스위치와 라우터의 차이|작성자 ykycome00

router 나 switch 라고 말하는 장비들은 엄밀히 말해 크게 두 가지 일을 한다. 특정 목적지로 가기 위해서는 어떤 경로들이 있는지에 대한 정보들을 수집하는 것과, 그 정보들 중에 실제로 선택된 경로를 기반해서 패킷을 전달하는 일. 전자를 경로(route) 를 알아내는 일이라고 해서 라우팅(routing) 이라고 하고 후자를 실제로 패킷을 전달(forward) 하는 일이라고 해서 포워딩(forwarding)  이라고 한다. 

우리가 보통 패킷을 전달하는 것을 라우팅이라고 부르는 경우가 많은데 이는 틀린 표현이다. 라우팅은 IP 패킷을 전달하는 것이라고 이해하고 있다면 이 역시 잘못된 것이다. 물론 많은 경우에 라우팅이 IP 패킷 전달을 의미하는 것으로 쓰이지만, 라우팅과 포워딩이라는 단어는 IP 와 같은 Layer 3 에 국한되는 것이 아닌 일반적인 개념으로 이해하는 것이 더 바람직하다.

원문보기: 
http://www.inven.co.kr/webzine/news/?news=168090#csidxe54e5be46d0d63e85d196cbe4d252d4 

[조사중] raspberry pi로 4G LTE router 만들기

4G Mobile Broadband Dongle (ZTE MF823)

https://filippobuletto.github.io/home-router-lte/#

qna : https://www.element14.com/community/thread/41419/l/raspberry-pi-b-wiith-usb-3g4g-dongle?displayFullThread=true

specs : http://www.ztemobiles.com.au/MF823.htm

sale : https://www.4gltemall.com/zte-mf823-4g-lte-fdd-datacard.html

4G LTE Modem sale : https://www.aliexpress.com/wholesale?catId=0&initiative_id=SB_20190617171040&SearchText=4g+lte+modem

—————————

how to unlock modem (dongle)huawei : https://appuals.com/unlock-huawei-modem-pocket-wifi-devices/

—————————-

LTE modem , wifi -> making router

https://lottoria.tistory.com/entry/Raspberry-PI%EC%97%90-LTE-%EB%AA%A8%EB%8E%80%EA%B3%BC-WiFi-%EB%A1%9C-%EB%AA%A8%EB%B0%94%EC%9D%BC-router-%EB%A7%8C%EB%93%A4%EA%B8%B0?category=488536

—————————-

3G/4G router

https://www.fastnetserv.com/how-to-make-a-raspberry-pi-3-as-a-3g4g-router/
korean cellular usim : https://www.clien.net/service/board/cm_rasp/11462384
내부 링크  alcatel dongle -> no needs to install ppp, wvdial

huawei 3G dongle error n solution : https://blog.naver.com/distrac/221137317824
 router GUI https://www.clien.net/service/board/cm_rasp/12508188?combine=true&q=%EB%9D%BC%EC%A6%88%EB%B2%A0%EB%A6%AC%ED%8C%8C%EC%9D%B4+%EB%9D%BC%EC%9A%B0%ED%84%B0&p=0&sort=recency&boardCd=&isBoard=false

LG U+ -> 2600 MHz

—————————-


dongle 스펙 비교 / manual / 통신사

python으로 arduino와 통신하기

아두이노와 블루투스 모듈간 시리얼 통신 도식화

가운데 두 선 ; 데이터 전송을 위한 선, TX(transmit)와 RX(receive)간의 연결

기본 시리얼 핀(빨간색)/ 시리얼 to USB 컨버터(노란색)

기본 시리얼(하드웨어시리얼) ; 보드 내장 회로를 통해 컴퓨터와 연결되는 역할, 특별한 경우 제외하고 다른 모듈 연결하지 말 것

컴퓨터는 USB 통신 규격을 사용하기 때문에 시리얼을 USB로 변환해줘야 함 -> 컨버터 내장되어 있음

다른 모듈과의 시리얼 통신은 SoftwareSerial 함수를 이용해 일반 핀을 시리얼 핀으로 이용할 수 있음

SoftwareSerial 사용 방법 : http://blog.naver.com/jamduino/220825414825

시리얼 통신을 하기 위한 파이썬 모듈/ winPython은 이것이 기본으로 설치되어 있음

import serial 하면 사용 가능 (모듈명은 pyserial이 아니라 그냥 serial)

시리얼 통신 객체 생성은 serial 모듈에 있는 serial클래스를 이용하면 된다. (serial.Serial)

class serial.Serial

__init__(     
port=None,     
baudrate=9600,     
bytesize=EIGHTBITS,     
parity=PARITY_NONE,     
stopbits=STOPBITS_ONE,     
timeout=None,     
xonxoff=False,     
rtscts=False,     
writeTimeout=None,     
dsrdtr=False,     
interCharTimeout=None
)

출처: https://studymake.tistory.com/79?category=645699 [스터디메이크]

  • port – 장치명. 윈도우즈에서는 ‘COM0’, ‘COM1’ 등이다.
  • baudrate – 보레이트(baud rate) 예를 들면 9600, 115200 등.
  • parity – 패리티비트. FIVEBITS, SIXBITS, SEVENVITS, EIGHTBITS 등이 가능하다.
  • stopbit – 정지비트. STOPBITS_ONE , STOPBITS_ONE_POINT_FIVE , STOPBITS_TWO 등이 가능하다.
  • timeout – 수신 시간 제한 설정
  • xonxoff – 소프트웨어 흐름 제어를 설정
  • rtscts – 하드웨어(RTS/CTS) 흐름 제어 설정
  • dsrdtr – 하드웨어(DSR/DTR) 흐름 제어 설정
  • writeTimeout – 송신 시간 제한 설정
  • interCharTimeout

예외 발생

  • ValueError – 입력 변수값에 오류가 있을 경우 발생
  • SerialException – 시리얼 통신 장치에 오류가 있을 경우 발생

포트만 지정해도 기본적으로 생성, 시리얼 통신 장치를 다 사용하였으면 obj.close() 호출하여 닫아줄 것.

[예제] python Arduino LED blinking

참고 사이트 : https://roboindia.com/tutorials/python-with-arduino

  • Arduino
  • 변수 선언

data

  • Setup

Serial.begin(speed) ; speed = baud rate (초당 얼마나 많은 심볼(Symbol, 의미 있는 데이터 묶음)을 전송할 수 있는가, 초당 신호(Signal) 요소의 수)

More detail about function :

https://www.arduino.cc/reference/ko/language/functions/communication/serial/begin/

Bit Rate와 Baud Rate의 정의 참고 :

pinmode(pin, mode) ; 특정핀을 입력 또는 출력으로 동작하도록 설정

more detail : https://www.arduino.cc/reference/ko/language/functions/digital-io/pinmode/

digitalWrite(pin, value) ; high 또는 low 값을 디지털 핀에 출력합니다.

핀이 pinMode()에서 OUTPUT -> 핀의 전압은 5V(HIGH) / 0V (LOW ;ground)

INPUT -> 입력 핀의 내부 풀업 저항을 활성화 (HIGH) / 비활성화 (LOW)

내장 풀업 저항을 활성화하기 위해서는 pinMode() 를 INPUT_PULLUP 으로 설정

pinMode() 를 OUTPUT 으로 설정하지 않고 LED를 핀에 연결하면, digitalWrite(HIGH) 가 불릴 때 LED 불빛이 흐리게 나타날 수 있습니다. 명시적으로 pinMode() 를 설정하지 않으면 digitalWrite() 는 내부 풀업 저항을 활성화시킬 것이고, 그것은 마치 전류를 제한하는 큰 저항처럼 동작할 것입니다.

More detail about function :

https://www.arduino.cc/reference/ko/language/functions/digital-io/digitalwrite/

Serial.println() ; serial에 글자 또는 숫자 출력 + 줄바꿈

Serial.print()와 Serial.println() 함수 :

  • Loop

While 내부 ; Serial.available() ; 결과값 = 시리얼 통신으로 수신한 데이터의 길이(바이트 단위)

코드 의미 = 수신한 데이터가 있으면 읽어와라

  • python

Error

  • Invalid syntax

Please note that 64-bit version or updated versions of python are not provide support for our Arduino Libraries. Even if your Computer is 64-bit machine. And this installation is applicable only for windows 32-bit or 64-bit OS.

Solution : Download 32-bit version python.

You may download it here :

http://www.python.org/ftp/python/2.7.9/python-2.7.9.msi

  • No module ‘arduino’

pyserial is python API module to read and write serial data.

Solution : Download pyserial.

You may download it here :

https://pypi.python.org/packages/47/c9/7802e11ab388ad1539de716649add8bb8ca8bdff660364b3a404f79c27b7/pyserial-2.7.win32.exe#md5=21555387937eeb79126cde25abee4b35

Result

Python 입력으로 LED control 가능

Time delay 내에 입력하면 반짝반짝도 가능 (0101010)

cf )

python은 idle로 실행 (다운로드 받은 코드도 idle로 실행)

Arduino down (https://www.arduino.cc/en/Main/Donate) just download

Arduino 컴퓨터에 연결하고 툴 – 포트 체크

Arduino 내장 blink (파일 – 예제 – 1. Basics – blink)

Serial monitor : 아두이노와 컴퓨터간에 메세지를 주고 받는 장치, 실행창 (단축키 Ctrl + Shift + M)